Declare a class or structure inside a method

In C #, is it possible to declare a class or structure inside a method, as in C ++?

for example C ++:

void Method() { class NewClass { } newClassObject; } 

I tried, but that did not allow me to do this.

+18
source share
3 answers

You can create an anonymous type, like so:

 var x = new { x = 10, y = 20 }; 

And get the (anonymous) type x with:

 x.getClass(); 

but other than that: no.

+15
source

Yes, you can declare a class inside a class , and they are called inner classes

 public class Foo { public class Bar { } } 

and how can you create an instance

 Foo foo = new Foo(); Foo.Bar bar = new Foo.Bar(); 

And within the method you can create an anonymous type object

 void Fn() { var anonymous= new { Name="name" , ID=2 }; Console.WriteLine(anonymous.Name+" "+anonymous.ID); } 
+10
source

You can declare them inside the class. , since your question is asked, but not inside the method , as indicated in the title of the question. Something like:

 public class MyClass { public class MyClassAgain { } public struct MyStruct { } } 
+7
source

All Articles