Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent C# syntax for C's inline anonymous struct definition?

Greetings Overflowers,

I know in C we can define a struct inline with the variable declaration so that the struct type is specific to this variable. This is instead of defining the type alone then declaring the variable to be of that struct type. Is this possible in C#?

Thank !

like image 689
geeko Avatar asked Apr 07 '11 09:04

geeko


People also ask

What is equivalent in C?

C *= A is equivalent to C = C * A. /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A.

What is the alternative to class for C?

The closest thing you can get is a struct . There is a feature in C intended to facilitate a sort of pseudo-inheritance, but it doesn't come close to an actual object-oriented class system.

Are there Generics in C?

It allows efficient development without the need to incorporate or switch to C++ or languages with builtin template systems, if desired. Using generics and templates in C can also make programs more type safe, and prevent improper access of memory.

Does C have new operator?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.


2 Answers

This is not possible in C#, however you can define an instance of an anonymous type like this:

var x = new { SomeField = 1, SomeOtherField = "Two" }; 

This would effectively be the same, giving you an instance of a type that is specific to that variable and cannot used outside the variable's scope.

like image 58
Avish Avatar answered Oct 05 '22 06:10

Avish


Simple answer: No, it is not possible.

like image 31
Daniel Hilgarth Avatar answered Oct 05 '22 04:10

Daniel Hilgarth