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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With