Alex Rivera | Logout

Declare a class or struct inside a method

Asked 2012-05-23T11:04:00.213
51

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.

Edit
Report

1 Answer

11

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);
}
answered 2012-05-23T11:10:36.643

Your Answer