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

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.


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


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);
}

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 };
}

Tags:

C#