Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Shorten syntax when repeatedly using type in generics?

If I'm using generics, like in this sample case, is there a way to shorten the syntax so I don't have to repeatedly type "CompanyLookupData"?

Func<CompanyLookupData, CompanyLookupData, bool> DELCompareNonKeyFieldsCompany =
    new Func<CompanyLookupData, CompanyLookupData, bool> 
    (CompanyLookupData.HasIdenticalNonKeyFieldsTo);

I had tried to do Type t = typeof(CopmanyLookupData), and use t in all of the locations, but that doesn't appear to work.

PS: while I'm open to a cleaner way of doing exactly what's shown, I'm more interested in a way to make generics syntax more concise in general.

like image 918
John Humphreys Avatar asked Jul 11 '12 13:07

John Humphreys


1 Answers

Yes, there are a few ways to achieve this:

If the variable is a local variable you can use the var keyword:

var DELCompareNonKeyFieldsCompany = new Func<CompanyLookupData, CompanyLookupData, bool>   (CompanyLookupData.HasIdenticalNonKeyFieldsTo);

However, if DELCompareNonKeyFieldsCompany is a class variable (a field or a property) you can let the compiler infer some of it for you by converting from a method group to a Func:

Func<CompanyLookupData, CompanyLookupData, bool> DELCompareNonKeyFieldsCompany = CompanyLookupData.HasIdenticalNonKeyFieldsTo;

If this type is to be used often, you may wish to create your own delegate type:

public delegate bool CompareCompanyNonKeyFields(CompanyLookupData, CompanyLookupData);

And use it like so:

CompareCompanyNonKeyFields DELCompareNonKeyFieldsCompany = CompanyLookupData.HasIdenticalNonKeyFieldsTo;

Alternatively if the type is only to be used within the one class, you could also create an alias to the type with the using keyword (although, personally, I find that this hinders the readability of the code):

using CompareCompanyNonKeyFields = System.Func<CompanyLookupData, CompanyLookupData, bool>;
...
 CompareCompanyNonKeyFields DELCompareNonKeyFieldsCompany = CompanyLookupData.HasIdenticalNonKeyFieldsTo;
like image 186
Rich O'Kelly Avatar answered Oct 20 '22 00:10

Rich O'Kelly