Reputation: 2125
I have a weird question about C#.
I have a static class to store methods as extensions. Then, I have the following extension:
public static bool fwHasData(this DataTable table)
{
return (table == null || table.Rows.Count == 0) ? true : false;
}
My question is: exists some way to avoid use the parentheses when I try to use the extension in my code?
Usage:
bool vHasData = MyDataTable.fwHasData(); // Works fine!
Expected usage:
bool vHasData = MyDataTable.fwHasData; // Removing the parentheses
Thanks a lot!
Upvotes: 4
Views: 1271
Reputation: 5701
Well, I just accidentally did this (I was so surprised, I googled it and that led me here):
Func<IEnumerable<IPlanHeader>> test = header.AsEnumerable;
With this extension method:
public static class ExtendGenericType
{
public static IEnumerable<T> AsEnumerable<T>(this T entity)
{
yield return entity;
}
}
...and lo-and-behold, no parenthesis! So please try this, and let me know:
Func<bool> vHasData = MyDataTable.fwHasData;
EDIT - Look, ultimately you will still need to convert the Func<bool>
to bool
using parenthesis at some point:
bool hasData = vHasData();
Upvotes: 1
Reputation: 17509
As suggested by others, the limitation is you can not have an extension property!
but, for the sake of achieving what you want. You can create a class deriving from DataTable (DataTable class is not sealed) and use this derived version in all your code.
Then you can extend DataTable with as many properties as you want!
Example:
public class DataTableEx : DataTable
{
public bool fwHasData
{
get
{
return (Rows.Count == 0) ? true : false;
}
}
}
Upvotes: 0
Reputation: 61349
No, this is not possible. Trying to call a method without parentheses doesn't make sense in C#.
You declared an extension method so of course you would need to call it as such (using the parenthesis).
You are accessing it as if it is an extension property which do not yet exist in C#. Regardless, you didn't declare it like a property, so even if they did exist you would still need to call it as a method.
Upvotes: 0
Reputation: 564433
This is not possible in C#. It would require some form of "extension property" syntax, which is not available in C#. It has been suggested in the past, but doesn't exist in the C# language today, nor in the upcoming C# 6 suggestions.
Upvotes: 10