Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic method and anonymous types

Tags:

c#

.net

generics

Would it be possible to create code like this:

private static string GetInsertString<TDto>()
{
    var type = typeof(TDto);
    var properties = type.GetProperties().Where(Where);
    var tableName = type.Name;

    return string.Format("INSERT INTO {0} ({1}) VALUES ({2});", 
    tableName, 
    string.Join(",", properties.Select(x => x.Name).ToArray()),
    string.Join(",", properties.Select(x => string.Format("@{0}", x.Name.ToLower())).ToArray()));
}

that works with anonymous types like this:

var point = new { X = 13, Y = 7 };

PS:

Output would be:

INSERT INTO Anonymous (X, Y) values (13, 7)

of course you may want to provide the table name.

like image 519
cs0815 Avatar asked Jun 25 '14 07:06

cs0815


People also ask

What are anonymous data types?

Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.

What is the difference between anonymous type and regular type?

The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.

What are anonymous types in C #?

Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.


1 Answers

You won't be able to specify the type parameter with an anonymous type, but if you pass it an object as a parameter, you can use type inference to get a hold of the type:

private static string GetInsertString<TDto>(TDto dto)
{
    var type = typeof(TDto);
    var propertyNames = type.GetProperties().Where(Where).Select(x => x.Name);

    return string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
        type.Name,
        string.Join(",", propertyNames),
        string.Join(",", propertyNames.Select(x => string.Format("@{0}", x.ToLower())));
}

Then call the method: var insertString = GetInsertString(new { X = 13, Y = 7 });

like image 66
khellang Avatar answered Oct 10 '22 01:10

khellang