Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a class or struct inside a method

Tags:

c#

.net

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.

like image 683
Thorin Oakenshield Avatar asked May 23 '12 11:05

Thorin Oakenshield


People also ask

Can you declare a class in a method?

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.

Can you declare a struct inside a class?

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.

Can you declare a struct inside a function?

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).


2 Answers

You can create an anonymous type like so:

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

but other than that: no.

like image 99
erikkallen Avatar answered Sep 21 '22 23:09

erikkallen


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); } 
like image 45
Sleiman Jneidi Avatar answered Sep 20 '22 23:09

Sleiman Jneidi