-2

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;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Kidus Tekeste
  • 651
  • 2
  • 10
  • 28
  • 1
    First structs cannot be static. Second if it were a class it would still work because you would have to create an instance (maybe your confusion is because there isn't a `new CustomerName()` call). Static means you would only access members via the class name. – juharr Nov 15 '16 at 20:33

1 Answers1

0

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?

Community
  • 1
  • 1
SteelSoul
  • 131
  • 2
  • 9