Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic syntax in C#

Tags:

Recently, I've come across C# examples that use a syntax that looks like the following:

var result = new { prop1 = "hello", prop2 = "world", prop3 = "." };

I really like it. It looks like JSON a bit. However, I don't know what this syntax is called. For that reason, I'm not sure how to learn more about it. I'm really interested in trying to figure out how to define arrays of objects within a result. For instance, what if I wanted to return an array of items for prop3? What would that look like? What is this syntax called?

like image 804
Eels Fan Avatar asked Mar 15 '13 14:03

Eels Fan


People also ask

What is dynamically in C?

Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime. C provides some functions to achieve these tasks.

What is the syntax of dynamic array in C?

Syntax. ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); This statement will allocate 400 bytes of RAM because int is 4 bytes long. Pointer ptr holds the address of the allocated memory's first byte.

What is dynamic structure in C?

Dynamic data structures are data structures that grow and shrink as you need them to by allocating and deallocating memory from a place called the heap. They are extremely important in C because they allow the programmer to exactly control memory consumption.

What is DMA in C with example?

The Dynamic memory allocation enables the C programmers to allocate memory at runtime. The different functions that we used to allocate memory dynamically at run time are − malloc () − allocates a block of memory in bytes at runtime. calloc () − allocating continuous blocks of memory at run time.


2 Answers

This is referred to as Anonymous Types in C#.

To return an array, you can simply inline it:

var result = new { prop1 = "hello", prop2 = "world", prop3 = new int[] {1,2,3} };

Or declare it beforehand and use it:

int[] array = new int[] {1,2,3};
var result = new { prop1 = "hello", prop2 = "world", prop3 = array};
like image 56
John Koerner Avatar answered Oct 27 '22 00:10

John Koerner


it's called anonymous types. For returning an array of objects in prop3 you would write

var result = new { prop1 = "hello", prop2 = "world", prop3 = new[] { "h", "e", "l", "l", "o" } };

I'm using strings but is the same for any type of object:

var result = new { prop1 = "hello", prop2 = "world", prop3 = new[] { new YourType(), new YourType(), new YourType() } };

Note that the type of the objects in the array is not necessary in the declaration of the array; you don't need to write new YourType[], the compiler don't need it and IMO it's cleaner to simply use new[]

like image 30
jorgehmv Avatar answered Oct 27 '22 01:10

jorgehmv