I guess I've seen it somewhere before, but now I can't remember nor find it. Is there a way to make a getter property with arguments?
I mean, as I can convert "float getSize();" to "float Size":
float getSize() {
return this.size;
}
float Size {
get { return this.size; }
}
Then, could I convert, for example, "float getSize(String unit);" to "float Size(String unit)" or something like that?
float getSize(String unit) {
return this.size;
}
float Size(String unit) {
get {
if (unit == Unit.Meters)
return this.size/100;
else
return this.size;
}
}
I think there's no really problem of using function at all, but may look better this way :P
To answer the question: No, it is not possible, and as already pointed out, a getter with a parameter would look just like a method.
The thing you are thinking about might be an indexed default property, which looks like this:
class Test
{
public string this[int index]
{
get { return index.ToString(); }
}
}
This allows you to index into an instance of Test, like this:
Test t = new Test();
string value = t[1];
Interestingly, having a property with parameter is possible in VB.NET, like this:
Public ReadOnly Property oPair(param As String) As Result
Get
'some code depends on param
End Get
End Property
It's not superior to a regular function, but sometimes it is nice to have such a possibility.
I know this is an old post, but I ran into wanting to do this today in C#. Whether that's a good thing or not is probably falling on the 'not' side. However, I ran across an interesting idea posted by Mark Jones at (https://social.msdn.microsoft.com/forums/en-US/5a25bc83-990e-4657-aa9c-69bca5158d48/overloaded-c-properties-with-arguments?prof=required), but I didn't quite like the feel of it.
So I wrote my own based on his (mine is in .Net 5.0 with Nullable = enable):
class ParameterizedProperty<T>
{
private readonly Func<int, T> getter;
private readonly Action<int, T> setter;
public T this[int index]
{
get => this.getter(index);
set => this.setter(index, value);
}
public ParameterizedProperty(Func<int, T> getter, Action<int, T> setter)
{
this.getter = getter;
this.setter = setter;
}
}
class NamedParameterizedProperty<T>
{
private readonly Func<int, T> indexedGetter;
private readonly Action<int, T> indexedSetter;
private readonly Func<string, T> namedGetter;
private readonly Action<string, T> namedSetter;
public T this[int index]
{
get => this.indexedGetter(index);
set => this.indexedSetter(index, value);
}
public T this[string name]
{
get => this.namedGetter(name);
set => this.namedSetter(name, value);
}
public NamedParameterizedProperty(Func<int, T> indexedGetter, Action<int, T> indexedSetter, Func<string, T> namedGetter, Action<string, T> namedSetter)
{
this.indexedGetter = indexedGetter;
this.indexedSetter = indexedSetter;
this.namedGetter = namedGetter;
this.namedSetter = namedSetter;
}
}
class ReadOnlyParameterizedProperty<T>
{
private readonly Func<int, T> getter;
public T this[int index] => this.getter(index);
public ReadOnlyParameterizedProperty(Func<int, T> getter)
{
this.getter = getter;
}
}
class ReadOnlyNamedParameterizedProperty<T>
{
private readonly Func<int, T> indexedGetter;
private readonly Func<string, T> namedGetter;
public T this[int index] => this.indexedGetter(index);
public T this[string name] => this.namedGetter(name);
public ReadOnlyNamedParameterizedProperty(Func<int, T> indexedGetter, Func<string, T> namedGetter)
{
this.indexedGetter = indexedGetter;
this.namedGetter = namedGetter;
}
}
So a little about my solution: I opted for Func<> & Action<> for the getters/setters because I didn't want this helper class to have to need any knowledge of underlying property it would be supporting. Instead, the class that owns the property would have public (or private) methods for get_X / set_X (or whatever naming convention you wish to use) that would handle everything - such as validation.
Now as to my use case for this: I had a class that has an internal array of a specific type. I have a default indexer property public primaryType this[int index], but it has a couple of other types that it understands and can convert to / from for primaryType. However, I can't do public otherType this[int index], and I didn't really want to do public methods called something like 'get_OtherType` & 'set_OtherType'.
These helper classes let me do something like:
public ParameterizedProperty<OtherType> OtherType { get; }
public MyClass()
{
this.OtherType = new(get_OtherType, set_OtherType);
}
private OtherType get_OtherType(int index)
{
/* validate index, convert PrimaryType at index to OtherType and return. */
}
private void set_OtherType(int index, OtherType value)
{
/* validate index, validate value, convert to PrimaryType and set to internal array. */
}
Then in other classes / UIs that use this class, where 'OtherType' is more convenient for them to work with then 'PrimaryType', I can have them doing things like myClass1.OtherType[0] = otherType;, but if they work with the primary type, then they can do myClass1[0] = primaryType - or if I just want to be consistent / explicit, I don't have a default indexer property, and I use a ParameterizedProperty for the primary type as well, IE: myClass1.PrimaryType[0] = primaryType;
Again, whether this is a good idea to go this route or not, I'm unsure.
It is possible for a class object to reasonably-efficiently have something that behaves as a named indexed property getter by having a property return a struct which simply holds a private reference to the class object and includes an indexed property getter which chains to a method in the class. Such a single-item structure can be generated at basically no cost (it can likely fit in a register, and will be loaded with a value that's in another register; the JIT may even be able to recognize that the same register can be used for both purposes), so if using such a getter makes code more readable that's a substantial argument in favor.
Unfortunately, the inability of struct members to indicate whether or not they modify the underlying structure makes it impossible to use the same approach for an indexed property setter. Even though it would be helpful it one could have have an OrderedCollection<T> with something like:
struct ByIndexAccessor {
OrderedCollection<T> owner;
ByIndexAccessor(OrderedCollection<T> o) { owner = o; }
T this[int index] {
get { return owner.handleGet(index); }
set { owner.handleSet(index, value); }
}
}
ByIndexAccessor ByIndex {
get {return new ByIndexAccessor(this); }
}
and say myCollection.ByIndex[3] = newThing;, C# would reject such code because it has no way of knowing that this particular indexed set implementation can safely be used on a read-only structure.
Related
Consider a situation:
I have a method which use DataRow:
public void MyMethod (DataRow input)
{
DoSomething(input["Name1"]);
}
But now I have some another input types with indexer which I want to pass to this method. St like:
public void MyMethod (AnyTypeWithIndexer input)
{
DoSomething(input["Name1"]);
}
But I haven't found anything like that. I tried IDictionary but it didn't work.
Is there any super type st like "Indexable" or anything with which I can replace the "AnyTypeWithIndexer"?
Note: I still need this method to pass the DataRow and also my custom class (which I want to implement).
Can anybody help?
Thanks.
No, unfortunately, there is no interface that automatically applies to "all classes with an indexer that takes a string argument and returns an object".
What you can do, however, is to create a "proxy class" that implements such an interface
yourself:
public interface IStringToObjectIndexable
{
object this[string index] { get; set; }
}
class DataRowWrapper : IStringToObjectIndexable
{
private readonly DataRow row;
public DataRowWrapper(DataRow row) => this.row = row;
public object this[string index]
{
get => row[index];
set => row[index] = value;
}
}
MyMethod can now be declared as follows:
public void MyMethod(IStringToObjectIndexable input)
{
DoSomething(input["Name1"]);
}
// Compatibility overload
public void MyMethod(DataRow input) => MyMethod(new DataRowWrapper(input));
You can use dynamic type, but you will need to be noticed about the disadvantages of dynamic, such as performance drawbacks because of DLR, and the fact that type safety should be on your shoulders
public class WithIndexer
{
public int this[string key] => 42;
}
public static async Task Main()
{
Dictionary<string, int> a = new Dictionary<string, int>();
a.Add("meow", 41);
Foo(a, "meow");
Foo(new WithIndexer(), "key");
}
private static void Foo(dynamic indexed, string key)
{
Console.WriteLine(indexed[key]);
}
Output:
41
42
Is there something inherently wrong with replacing
IDictionary<int, IEnumerable<string>>
with
ILookup<int, string>
I much prefer ILookup over IDictionary because of its more 'honest' interface and immutability.
However, I discovered that ILookup is unable to hold empty collections, so keys containing empty collections are simply do not exist in it. This is problem, because I also would like ILookup to convey information about all possible keys (even though some of them might be empty), so I can go like this:
var statistics = from grouping in myLookup
select new {grouping.Key, grouping.Count()};
which works with dictionary of enumerables, but unfortunately does not work with ILookup. It is just impossible to have entries where grouping.Count()==0, as with IDictionary.
As John Skeet states,
There’s one other important difference between a lookup and a dictionary: if you ask a lookup for the sequence corresponding to a key which it doesn’t know about, it will return an empty sequence, rather than throwing an exception. (A key which the lookup does know about will never yield an empty sequence.)
Now, what is wrong if ILookup allowed empty groupings? In order to have the best of both worlds I am about to add Filter() extension method for ILookup that does just this, but need to resolve a problem that Linq does not allow to create empty IGroupings (so I have to implement my own class), but I feel that maybe I am doing something against design principles of Linq.
Example
Two options:
1) you could create a nice, straightforward singleton-esque EmptyLookup class as follows:
var empty = EmptyLookup<int, string>.Instance;
// ...
public static class EmptyLookup<TKey, TElement>
{
private static readonly ILookup<TKey, TElement> _instance
= Enumerable.Empty<TElement>().ToLookup(x => default(TKey));
public static ILookup<TKey, TElement> Instance
{
get { return _instance; }
}
}
2) You can create a singleton class for empty lookups.
public sealed class EmptyLookup<T, K> : ILookup<T, K>
{
private static readonly EmptyLookup<T, K> _instance
= new EmptyLookup<T, K>();
public static EmptyLookup<T, K> Instance
{
get { return _instance; }
}
private EmptyLookup() { }
public bool Contains(T key)
{
return false;
}
public int Count
{
get { return 0; }
}
public IEnumerable<K> this[T key]
{
get { return Enumerable.Empty<K>(); }
}
public IEnumerator<IGrouping<T, K>> GetEnumerator()
{
yield break;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
yield break;
}
}
then you can write code like this:
var x = EmptyLookup<int, int>.Instance;
/*The benefit of creating a new class is that you can use the "is" operator and check for type equality:*/
if (x is EmptyLookup<,>) {
// ....
}
There is no wrong in keeping empty groupings is lookup, it's just that lookup does not support it because of it's nature in Linq.
You have to create an extension method by yourself.
I would like to be able to do something like this for setting up a
mesh data structure.
IReadOnlyList<Point> points;
IReadOnlyList<IReadOnlyList<int>> triangles;
where the triangles are indices into the points list. Given an index
of a triangle ''ti'' we can find the points easily
IEnumerable<Point> points = triangles[ti].Select(pi=>points[pi])
However I would like to be able to define a convienience structure
IReadOnlyList<IReadOnlyList<Point>> trianglesAsPoints;
so I can do
IEnumerable<Point> points = triangles[ti]
The obvious way to do this would be to create a linq like selector
IReadOnlyList<T> Select( this IReadOnlyList<U> This
, Func<U,T> selector)
which returns an instance whose class overrides the following method and
invokes the selector
public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
{
// Summary:
// Gets the element at the specified index in the read-only list.
//
// Parameters:
// index:
// The zero-based index of the element to get.
//
// Returns:
// The element at the specified index in the read-only list.
T this[int index] { get; }
}
Does such a factory exist anywhere in the standard libs or nuget for this pattern?
Note I do not want IEnumerable as a result because I would lose the indexing ability
and the Count property, I just want to lazily transform the value which means not
copying all the values to a new list instance up front.
I don't believe there's anything which does this in the framework, no. It's obviously reasonably easy to implement yourself, but I believe you'll have to do it. It's entirely possible that there are 3rd party libraries which do it, but as IReadOnlyCollection was only in .NET 4.5 it's less likely than if the interface had existed for a while.
I'd suggest calling it something other than Select though - I'd use ProjectView or something similar. Of course that means it wouldn't work with LINQ query expressions, but it will be clearer to anyone reading the code that it's not just Enumerable.Select.
Here is a hand rolled solution to the problem
public static class CollectionMixins
{
private class ReadOnlyListProjection<U,T> : IReadOnlyList<T>
{
public Func<U,T> Selector { get; private set; }
public IList<U> List { get; private set; }
public ReadOnlyListProjection(IList<U> list, Func<U, T> selector)
{
List = list;
Selector = selector;
}
public T this[int index]
{
get { return Selector(List[index]); }
}
public int Count
{
get { return List.Count; }
}
public IEnumerator<T> GetEnumerator()
{
return List.Select(Selector).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return List.Select(Selector).GetEnumerator();
}
}
public static IReadOnlyList<T> ProjectReadOnly<U, T>(this IList<U> This, Func<U, T> fn)
{
return new ReadOnlyListProjection<U, T>(This, fn);
}
}
so I can now do
IList<int> foo = new List<int>{0,1,2};
IReadOnlyList<string> bar = foo.ProjectReadOnly( x=>x.ToString() );
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get null instead of the KeyNotFoundException accessing Dictionary value by key?
I currently have lots of Dictionary<string, T> uses in my project, and most of them look like so:
if (myDic.ContainsKey("some key"))
localVar = myDic["some key"];
It's not very effecient too, as it does two calls to the dictionary, which can be resource consuming. TryGetValue() is a cool thing, but it just doesn't do it in one line.
I just want to get null if there is no such key from var v = myDic[key]. How do I do that?
You may use an extension method with TryGetValue:
public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
where U : class
{
U value;
dict.TryGetValue(key, out value);
return value;
}
thanks to which you'll be able to write
somedict.GetValueByKeyOrNull("key1")
In the end trying to do this very thing I came up with a variant using a deriving from dictionary class with explicit interface implementation: How to get null instead of the KeyNotFoundException accessing Dictionary value by key?
That is
public interface INullValueDictionary<T, U>
where U : class
{
U this[T key] { get; }
}
public class NullValueDictionary<T, U> : Dictionary<T, U>, INullValueDictionary<T, U>
where U : class
{
U INullValueDictionary<T, U>.this[T key]
{
get
{
U val;
dict.TryGet(key, out val);
return val;
}
}
}
and use it instead of the original dictionary everywhere:
//create some dictionary
NullValueDictionary<int, string> dict = new NullValueDictionary<int, string>
{
{1,"one"}
};
//have a reference to the interface
INullValueDictionary<int, string> idict = dict;
string val = idict[2]; // null
val = idict[1]; // "one"
I don't like to deal with null so my implementation will look like this:
interface Maybe<T> {
bool HasValue {get;}
T Value {get;}
}
class Nothing<T> : Maybe<T> {
public bool HasValue { get { return false; } }
public T Value { get { throw new Exception(); } }
public static const Nothing<T> Instance = new Nothing<T>();
}
class Just<T> : Maybe<T> {
private T _value;
public bool HasValue { get { return true; } }
public T Value { get { return _value; } }
public Just(T val) {
_value = val;
}
}
Maybe is a object that can contain value or not. Note that Nothing class contains static field Instance. We can use this value instead of creating new value each time we need to return Nothing from function.
Now, we need to create our own dictionary class:
class MyDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> _dict;
...
public Maybe<TValue> this[TKey key] {
TValue val;
if (_dict.TryGetValue(key, out val)) {
return new Just<TValue>(val);
return Nothing<TValue>.Instance;
}
}
Advantage of this approach is not clear, because C# doesn't have pattern matching. But it can be emulated with dynamic:
void ProcessResult(Just<string> val) {
Console.WriteLine(val);
}
void ProcessResult(Nothing<string> n) {
Console.WriteLine("Key not found");
}
var dict = new MyDictionary<string, string>();
...
dynamic x = dict["key"];
ProcessResult(x);
I think that this is very clear way to express the fact that dictionary can't always return meaningful result. Also it is obvious for reader that function overload ProcessResult(Just<T>) will be called only for values that present in dictionary and other overload will be called in case when key is not found.
Pros:
Type serves as a specification.
Dictionary can contain both value and reference types.
Cons:
More keystrokes.
Little more complexity to deal with.
I decided to do it like this:
class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new TValue this[TKey key]
{
get
{
TValue value;
return TryGetValue(key, out value) ? value : default(TValue);
}
set { base[key] = value; }
}
}
It lets me use it like any other dictionary, through square brackets. Since I'm not going to use this with value types as TValue, I think it's good enough a solution.
I'm writing a simple proof of concept for what should be, in essence, a parser generator.
Basically I'm looking for a way that I can write a function that will return a function that converts from a string to some object of a given type - I want to be able to do the following in essence:
Func<string, double> ConvertToDouble = BuildConverter(typeof(0.0));
Obviously this is a pretty contrived example - but if I can do the simple version then I ought to be able to do the more complicated version!
FWIW, what I'm ultimately trying to do is to map a string of values onto a class, but to make it as flexible as possible, I want to do it by having a function that will return a function that does the conversion. In functional terms, I think I want something that looks like this:
a -> (string -> a)
As a first try, I've tried doing this:
public static Func<string, T> BuildParser<T>(T t)
{
if (t is String)
return new Func<string, T>(x => x.ToString());
if (t is double)
return new Func<string, T>(x => double.Parse(x));
}
Which doesn't work at all, but it leaves me feeling a bit stuck as to what approach I ought to be taking - so any help at all would be greatly appreciated!
You cannot mix class with struct types. Beyond that, it will work.
See the code below:
private void Testing() {
var func = BuildParserStruct<double>();
double value = func("5");
}
public static Func<string, T> BuildParserClass<T>() where T : class
{
return x => x as T;
}
public static Func<string, T> BuildParserStruct<T>() where T : struct
{
return (x => (T)Convert.ChangeType(x, typeof(double)));
}
I'm guessing that you want specific behaviors verified at compile time. Why not just call Convert or write individual methods to use? All that your if statements accomplish is to take role of the programmer who should be chosing the appropriate conversion method.
If you want behaviors chosen at runtime, you should return Func<string, object>, and make the method non-generic.
The issue with using a generic Type T in the method is that T is fixed for each call to the method, and the logic in the method supposes T to vary in a single call (in one case T is a string, in another case T is a decimal). The compiler cannot sort this out - it would need to allow both returnable instances to have the same type.
I'm not certain of exactly what you're trying to do, but would something like this help?
var stringParser = GetParser<string>();
string s = stringParser("test");
var doubleParser = GetParser<double>();
double d = doubleParser("42");
// ...
public static Func<string, T> GetParser<T>()
{
return (Func<string, T>)_parserCache[typeof(T)];
}
private static readonly Dictionary<Type, Delegate> _parserCache =
new Dictionary<Type, Delegate>
{
{ typeof(string), new Func<string, string>(x => x) },
{ typeof(double), new Func<string, double>(x => double.Parse(x)) }
// etc
};
ADO.Net has an Execute Scalar function that always bothered me because it returns an object. You can write a generic wrapper function to return the appropriate type. Of course this assumes that you know what type will be returned.
Somewhat simplified:
public T ExecuteScalar<T>()
{
return (T)Command.ExecuteScalar();
}