Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a local struct, within a method, in C#?

Tags:

c#

People also ask

Can I define a struct inside a function C?

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

Can you define a struct in a function?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Show activity on this post. No, but you can in c++ struct!

Can you define 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 struct contain methods?

Structures can have methods, fields, indexers, properties, operator methods, and events. Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.


I believe it's not permitted to define named types within a method. As to why, I'll have to speculate. If a type is not going to be used outside, then its existence probably cannot be justified.

You can however define anonymous type variables within a method. It will somewhat resembles structures. A compromise.

public void SomeMethod ()
{
    var anonymousTypeVar = new { x = 5, y = 10 };
}

It is a little late but this is my solution for lists - using anonymous vars as the structs inside of methods:

var list = new[] { new { sn = "a1", sd = "b1" } }.ToList(); // declaring structure
list.Clear();                                               // clearing dummy element
list.Add(new { sn="a", sd="b"});                            // adding real element
foreach (var leaf in list) if (leaf.sn == "a") break;       // using it

Anonymous elements (sn and sd) are somehow read only.


You could do something like this using anonymous types. MSDN examples below:

var v = new { Amount = 108, Message = "Hello" };

or

var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
    Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}

Since C# 7.0, you can use value tuples if you want a lightweight data structure with named fields. They can be used not only locally inside methods, but also in parameters, returns, properties, fields, etc. You can use local functions to somewhat emulate struct methods.

var book = (id: 65, pageCount: 535);        // Initialization A
(int id, int pageCount) book2 = (44, 100);  // Initialization B
Console.WriteLine($"Book {book.id} has {book.pageCount} pages.");

(int id, int pageCount) = book;  // Deconstruction into variables
Console.WriteLine($"Book {id} has {pageCount} pages.");

Here book is of type System.ValueTuple<int, int> (a generic struct).


No, this is not possible. If you are using .net 4.0, you could use Tuple<T1, ..., Tn> to replicate such a thing.

I don't see the reason why you would need such a struct - just use variables with speaking names and this shouldn't be any problem at all. In combination with explicit declaration using the class names there is very little space for ambiguity.


You can define an anonymous type within your method and use it. The anonymous type will be readonly, so it gets you the immutability that is desired of structs. It will not explicitly be a struct, but it will be fully defined and contained within your method.

var myLocalType = new 
    {
        SomeValue = "Foo",
        SomeId = 14
    };