In C#, is it possible to declare a class or struct inside a method, as in C++?
e.g. C++:
void Method() { class NewClass { } newClassObject; }
I have tried, but it's not allowing me to do so.
In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.
Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.
Yes, the standard allows this, and yes, the name you create this way is only visible inside the function (i.e., it has local scope, just like when you define int i; , i has local scope).
You can create an anonymous type like so:
var x = new { x = 10, y = 20 };
but other than that: no.
Yes, it is possible to declare a class
inside a class
and these are called inner classes
public class Foo { public class Bar { } }
and this how you can create an instance
Foo foo = new Foo(); Foo.Bar bar = new Foo.Bar();
And within a method you can create an object of anonymous
type
void Fn() { var anonymous= new { Name="name" , ID=2 }; Console.WriteLine(anonymous.Name+" "+anonymous.ID); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With