Kidus Tekeste Kidus Tekeste - 24 days ago 7
C# Question

Why does the C# compiler not complain when we use struct function inside the static methods without defining them static?

Why does the compiler not complain when we use struct function inside the static methods without defining them static?

Example:

struct CustomerName{
Public String firstname, lastname;
Public String Name() => firstname + " " +lastname;
}
Public static void main(){
CustomerName MyName ;
MyName.firstname = "Kidus";
MyName.lastname = "Tekeste";
Console.WriteLine(MyName.Name());
}


This works fine in visual studio but I wonder why it worked with out it being made static. like this:

static struct CustomerName{
Public String firstname, lastname;
Public String Name() => firstname + " " +lastname;
}

Answer

If it would have been a class, would it be clearer? Same behaviour.

Firstly, struct cant be static Simple explanation

You declare and define a struct somewhere. By not defining it as static You essentially say it can be instantiated to an object of type CustomerName. In your Main() you instantiate an object of this type and call it MyName and assign values to its fields. Works just as intended, don't you agree?