Syntax for implicit operator with class indexer - c#

I am looking for the correct syntax to use an implicit operator on a class that uses an indexer to acess a private Dictionary:
[System.Serializable]
public class MyClass : IEnumerable
{
private Dictionary<string, object> vars = new Dictionary<string, object>();
public object this[string key]
{
get
{
if(vars.ContainsKey(key))
{
return (object)vars[key];
}
else
{
return null;
}
}
set
{
object o = value;
if(!vars.ContainsKey(key))
{
vars.Add(key, o);
}
else if(value == null)
{
vars.Remove(key);
}
else
{
vars[key] = o;
}
}
}
/*some code*/
public static implicit operator bool(WorldVars w, string i)
{
if(w[i] != null)
{
return true;
}
else
{
return false;
}
}
}
Right now the use is pretty straight forward
MyClass[anykey] = myValue
but I'd like to implement a quicker way to test the presence of a value, like:
if(MyClass[anykey])
{ //logic }

As commenter Eric notes, the semantics of your class would be completely broken if you were able to achieve what you're asking for. The whole point of the indexer is so that when you write the expression myClass[anyKey], it evaluates to the value that your class associates with anyKey.
If you were to change the implementation so that it simply returned a bool value representing containment, then you'd be stuck having to implement some other mechanism to actually retrieve the value (e.g. a separate method). Additionally, it would also raise the question of what the setter should do.
Given the implementation you show, it seems to me that writing if (myClass[anyKey] != null) is not really inconvenient, and it seems reasonably expressive to me. That is, it is a reasonable way for the code to clearly express its intent.
That said, if you did want something more expressive, it would not be unreasonable to write a ContainsKey() method in your class for the purpose:
public bool ContainsKey(string key) { return vars.ContainsKey(key); }
Then you could check for the key's presence like:
if (myClass.ContainsKey[anyKey]) { ... }
Finally, the code you posted should work acceptably well, but it seems overly verbose and inconsistent to me. IMHO, a better way to write your indexer methods would be something like this:
public object this[string key]
{
get
{
object o;
return vars.TryGetValue(key, out o) ? o : null;
}
set
{
if (value != null)
{
vars[key] = value;
}
else
{
vars.Remove(key);
}
}
}
That implementation avoids things like:
Redundant check for containment when getting a value
Copying value into local variable unnecessarily when setting a value
Having two different lines of code that each both have the effect of setting the value for a key in the dictionary

Related

Using derived type for recursive tree method

I have a class BinaryTree<T> that looks like this:
class BinaryTree<T>
where T : IComparable
{
protected BinaryTree<T>? _left;
protected BinaryTree<T>? _right;
protected BinaryTree<T>? _root;
protected T _value;
public T Value
{
get { return _value; }
set { _value = value; }
}
public BinaryTree<T>? Left
{
get { return _left; }
set { _left = value; }
}
public BinaryTree<T>? Right
{
get { return _right; }
set { _right = value; }
}
public BinaryTree<T>? Root
{
get { return _root; }
set { _root = value; }
}
public BinaryTree() { }
public BinaryTree(T value, BinaryTree<T>? left = null, BinaryTree<T>? right = null, BinaryTree<T>? root = null)
{ ... }
public List<T> PreOrder()
{ ... }
public List<T> InOrder()
{ ... }
public List<T> PostOrder()
{ ... }
}
And a dervied class BinarySearchTree that implements the Search method:
class BinarySearchTree : BinaryTree<int>
{
public BinarySearchTree() : base() { }
public Boolean Search(int value)
{
if (Value.CompareTo(value) == 0) return true;
if ((Left is not null) && (Value.CompareTo(value) > 0)) { return Left.Search(value); }
else if ((Right is not null) && (Value.CompareTo(value) > 0)) { return Right.Search(value); }
else { return false; }
}
}
Left.Search (and analagously Right) won't work because Left isn't of type BinarySearchTree, but rather BinaryTree<int>. I know that you can solve this by overriding _left, _right, Left and Right in BinaryTree, but that seems redundant since the new code isn't doing anything functionally different. I also know that we could just move Search to BinaryTree in this case, but that isn't the point; in the case of more complicated methods that I only want to have in a derived class it seems like this kind of functionality should be available somewhere.
My initial idea was to try to set the type of _left and _right in the base class to whatever the derived class would be. It doesn't seem like that's possible though; I can get the type as string using GetType() but I can't define a property with that type.
First of all, you should probably use composition instead of inheritance, i.e. make BinaryTree<int> a field or property of BinarySearchTree. Composition tend to make code easier to use and reason about since you don't have to worry about complex inheritance hierarchies.
class BinarySearchTree
{
private BinaryTree<int> root;
}
You can then make your search method take a node as input parameter, commonly using an private method for recursion, and a public method that uses the root:
class BinarySearchTree
{
private BinaryTree<int> root;
public Boolean Search(int value) => Search(root, value);
private Boolean Search(BinaryTree<int> node, int value)
{
...
}
}
However, there are some things other things I would consider fixing.
Recursive techniques have some problems. If the tree is poorly balanced it can lean to stack overflows. I would recommend thinking about using a iterative technique instead. That should be fairly simple for a binary search method.
Use a IComparer<T> parameter instead of IComparable restriction, and an overload that uses Comparer<T>.Default if the user does not specifically give you one. This is a good compromise between flexibility and ease of use, and is the pattern most of the framework uses.
Use a functional approach rather than a class based approach. That tend to make the code easier to reuse, since you are not tied to a specific tree type. A signature might for example look something like this:
public static bool BinarySearch<T>(T current, T value, Func<T, (T? Left, T? Right)> selector, IComparer<T> comparer)
If you are handling large trees of primitive types, it is often more useful to describe the tree using an array. Objects have some overhead, and if you have a very large amount of ints, that overhead will dominiate. Sometimes, using arrays and indexes to that array can be a better solution when dealing with lots of data, a typical example would be something like a heap.

Cleaner way to do a null check in C#? [duplicate]

This question already has answers here:
C# elegant way to check if a property's property is null
(20 answers)
Closed 9 years ago.
Suppose, I have this interface,
interface IContact
{
IAddress address { get; set; }
}
interface IAddress
{
string city { get; set; }
}
class Person : IPerson
{
public IContact contact { get; set; }
}
class test
{
private test()
{
var person = new Person();
if (person.contact.address.city != null)
{
//this will never work if contact is itself null?
}
}
}
Person.Contact.Address.City != null (This works to check if City is null or not.)
However, this check fails if Address or Contact or Person itself is null.
Currently, one solution I could think of was this:
if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)
{
// Do some stuff here..
}
Is there a cleaner way of doing this?
I really don't like the null check being done as (something == null). Instead, is there another nice way to do something like the something.IsNull() method?
In a generic way, you may use an expression tree and check with an extension method:
if (!person.IsNull(p => p.contact.address.city))
{
//Nothing is null
}
Full code:
public class IsNullVisitor : ExpressionVisitor
{
public bool IsNull { get; private set; }
public object CurrentObject { get; set; }
protected override Expression VisitMember(MemberExpression node)
{
base.VisitMember(node);
if (CheckNull())
{
return node;
}
var member = (PropertyInfo)node.Member;
CurrentObject = member.GetValue(CurrentObject,null);
CheckNull();
return node;
}
private bool CheckNull()
{
if (CurrentObject == null)
{
IsNull = true;
}
return IsNull;
}
}
public static class Helper
{
public static bool IsNull<T>(this T root,Expression<Func<T, object>> getter)
{
var visitor = new IsNullVisitor();
visitor.CurrentObject = root;
visitor.Visit(getter);
return visitor.IsNull;
}
}
class Program
{
static void Main(string[] args)
{
Person nullPerson = null;
var isNull_0 = nullPerson.IsNull(p => p.contact.address.city);
var isNull_1 = new Person().IsNull(p => p.contact.address.city);
var isNull_2 = new Person { contact = new Contact() }.IsNull(p => p.contact.address.city);
var isNull_3 = new Person { contact = new Contact { address = new Address() } }.IsNull(p => p.contact.address.city);
var notnull = new Person { contact = new Contact { address = new Address { city = "LONDON" } } }.IsNull(p => p.contact.address.city);
}
}
Your code may have bigger problems than needing to check for null references. As it stands, you are probably violating the Law of Demeter.
The Law of Demeter is one of those heuristics, like Don't Repeat Yourself, that helps you write easily maintainable code. It tells programmers not to access anything too far away from the immediate scope. For example, suppose I have this code:
public interface BusinessData {
public decimal Money { get; set; }
}
public class BusinessCalculator : ICalculator {
public BusinessData CalculateMoney() {
// snip
}
}
public BusinessController : IController {
public void DoAnAction() {
var businessDA = new BusinessCalculator().CalculateMoney();
Console.WriteLine(businessDA.Money * 100d);
}
}
The DoAnAction method violates the Law of Demeter. In one function, it accesses a BusinessCalcualtor, a BusinessData, and a decimal. This means that if any of the following changes are made, the line will have to be refactored:
The return type of BusinessCalculator.CalculateMoney() changes.
The type of BusinessData.Money changes
Considering the situation at had, these changes are rather likely to happen. If code like this is written throughout the codebase, making these changes could become very expensive. Besides that, it means that your BusinessController is coupled to both the BusinessCalculator and the BusinessData types.
One way to avoid this situation is rewritting the code like this:
public class BusinessCalculator : ICalculator {
private BusinessData CalculateMoney() {
// snip
}
public decimal CalculateCents() {
return CalculateMoney().Money * 100d;
}
}
public BusinessController : IController {
public void DoAnAction() {
Console.WriteLine(new BusinessCalculator().CalculateCents());
}
}
Now, if you make either of the above changes, you only have to refactor one more piece of code, the BusinessCalculator.CalculateCents() method. You've also eliminated BusinessController's dependency on BusinessData.
Your code suffers from a similar issue:
interface IContact
{
IAddress address { get; set; }
}
interface IAddress
{
string city { get; set; }
}
class Person : IPerson
{
public IContact contact { get; set; }
}
class Test {
public void Main() {
var contact = new Person().contact;
var address = contact.address;
var city = address.city;
Console.WriteLine(city);
}
}
If any of the following changes are made, you will need to refactor the main method I wrote or the null check you wrote:
The type of IPerson.contact changes
The type of IContact.address changes
The type of IAddress.city changes
I think you should consider a deeper refactoring of your code than simply rewriting a null check.
That said, I think that there are times where following the Law of Demeter is inappropriate. (It is, after all, a heuristic, not a hard-and-fast rule, even though it's called a "law.")
In particular, I think that if:
You have some classes that represent records stored in the persistence layer of your program, AND
You are extremely confident that you will not need to refactor those classes in the future,
ignoring the Law of Demeter is acceptable when dealing specifically with those classes. This is because they represent the data your application works with, so reaching from one data object into another is a way of exploring the information in your program. In my example above, the coupling caused by violating the Law of Demeter was much more severe: I was reaching all the way from a controller near the top of my stack through a business logic calculator in the middle of the stack into a data class likely in the persistence layer.
I bring this potential exception to the Law of Demeter up because with names like Person, Contact, and Address, your classes look like they might be data-layer POCOs. If that's the case, and you are extremely confident that you will never need to refactor them in the future, you might be able to get away with ignoring the Law of Demeter in your specific situation.
in your case you could create a property for person
public bool HasCity
{
get
{
return (this.Contact!=null && this.Contact.Address!= null && this.Contact.Address.City != null);
}
}
but you still have to check if person is null
if (person != null && person.HasCity)
{
}
to your other question, for strings you can also check if null or empty this way:
string s = string.Empty;
if (!string.IsNullOrEmpty(s))
{
// string is not null and not empty
}
if (!string.IsNullOrWhiteSpace(s))
{
// string is not null, not empty and not contains only white spaces
}
A totally different option (which I think is underused) is the null object pattern. It's hard to tell whether it makes sense in your particular situation, but it might be worth a try. In short, you will have a NullContact implementation, a NullAddress implementation and so on that you use instead of null. That way, you can get rid of most of the null checks, of course at the expense at some thought you have to put into the design of these implementations.
As Adam pointed out in his comment, this allows you to write
if (person.Contact.Address.City is NullCity)
in cases where it is really necessary. Of course, this only makes sense if city really is a non-trivial object...
Alternatively, the null object can be implemented as a singleton (e.g., look here for some practical instructions concerning the usage of the null object pattern and here for instructions concerning singletons in C#) which allows you to use classical comparison.
if (person.Contact.Address.City == NullCity.Instance)
Personally, I prefer this approach because I think it is easier to read for people not familiar with the pattern.
Update 28/04/2014: Null propagation is planned for C# vNext
There are bigger problems than propagating null checks. Aim for readable code that can be understood by another developer, and although it's wordy - your example is fine.
If it is a check that is done frequently, consider encapsulating it inside the Person class as a property or method call.
That said, gratuitous Func and generics!
I would never do this, but here is another alternative:
class NullHelper
{
public static bool ChainNotNull<TFirst, TSecond, TThird, TFourth>(TFirst item1, Func<TFirst, TSecond> getItem2, Func<TSecond, TThird> getItem3, Func<TThird, TFourth> getItem4)
{
if (item1 == null)
return false;
var item2 = getItem2(item1);
if (item2 == null)
return false;
var item3 = getItem3(item2);
if (item3 == null)
return false;
var item4 = getItem4(item3);
if (item4 == null)
return false;
return true;
}
}
Called:
static void Main(string[] args)
{
Person person = new Person { Address = new Address { PostCode = new Postcode { Value = "" } } };
if (NullHelper.ChainNotNull(person, p => p.Address, a => a.PostCode, p => p.Value))
{
Console.WriteLine("Not null");
}
else
{
Console.WriteLine("null");
}
Console.ReadLine();
}
The second question,
I really don't like the null check being done as (something == null). Instead, is there another nice way to do something like the something.IsNull() method?
could be solved using an extension method:
public static class Extensions
{
public static bool IsNull<T>(this T source) where T : class
{
return source == null;
}
}
If for some reason you don't mind going with one of the more 'over the top' solutions, you might want to check out the solution described in my blog post. It uses the expression tree to find out whether the value is null before evaluating the expression. But to keep performance acceptable, it creates and caches IL code.
The solution allows you do write this:
string city = person.NullSafeGet(n => n.Contact.Address.City);
You can write:
public static class Extensions
{
public static bool IsNull(this object obj)
{
return obj == null;
}
}
and then:
string s = null;
if(s.IsNull())
{
}
Sometimes this makes sense. But personally I would avoid such things... because this is is not clear why you can call a method of the object that is actually null.
Do it in a separate method like:
private test()
{
var person = new Person();
if (!IsNull(person))
{
// Proceed
........
Where your IsNull method is
public bool IsNull(Person person)
{
if(Person != null &&
Person.Contact != null &&
Person.Contact.Address != null &&
Person.Contact.Address.City != null)
return false;
return true;
}
Do you need C#, or do you only want .NET? If you can mix another .NET language, have a look at Oxygene. It's an amazing, very modern OO language that targets .NET (and also Java and Cocoa as well. Yep. All natively, it really is quite an amazing toolchain.)
Oxygene has a colon operator which does exactly what you ask. To quote from their miscellaneous language features page:
The Colon (":") Operator
In Oxygene, like in many of the languages it
was influenced by, the "." operator is used to call members on a class
or object, such as
var x := y.SomeProperty;
This "dereferences" the object contained in
"y", calls (in this case) the property getter and returns its value.
If "y" happens to be unassigned (i.e. "nil"), an exception is thrown.
The ":" operator works in much the same way, but instead of throwing
an exception on an unassigned object, the result will simply be nil.
For developers coming from Objective-C, this will be familiar, as that
is how Objective-C method calls using the [] syntax work, too.
... (snip)
Where ":" really shines is when accessing properties in a chain, where
any element might be nil. For example, the following code:
var y := MyForm:OkButton:Caption:Length;
will run without error, and
return nil if any of the objects in the chain are nil — the form, the
button or its caption.
try
{
// do some stuff here
}
catch (NullReferenceException e)
{
}
Don't actually do this. Do the null checks, and figure out what formatting you can best live with.
I have an extension that could be useful for this; ValueOrDefault(). It accepts a lambda statement and evaluates it, returning either the evaluated value or a default value if any expected exceptions (NRE or IOE) are thrown.
/// <summary>
/// Provides a null-safe member accessor that will return either the result of the lambda or the specified default value.
/// </summary>
/// <typeparam name="TIn">The type of the in.</typeparam>
/// <typeparam name="TOut">The type of the out.</typeparam>
/// <param name="input">The input.</param>
/// <param name="projection">A lambda specifying the value to produce.</param>
/// <param name="defaultValue">The default value to use if the projection or any parent is null.</param>
/// <returns>the result of the lambda, or the specified default value if any reference in the lambda is null.</returns>
public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection, TOut defaultValue)
{
try
{
var result = projection(input);
if (result == null) result = defaultValue;
return result;
}
catch (NullReferenceException) //most reference types throw this on a null instance
{
return defaultValue;
}
catch (InvalidOperationException) //Nullable<T> throws this when accessing Value
{
return defaultValue;
}
}
/// <summary>
/// Provides a null-safe member accessor that will return either the result of the lambda or the default value for the type.
/// </summary>
/// <typeparam name="TIn">The type of the in.</typeparam>
/// <typeparam name="TOut">The type of the out.</typeparam>
/// <param name="input">The input.</param>
/// <param name="projection">A lambda specifying the value to produce.</param>
/// <returns>the result of the lambda, or default(TOut) if any reference in the lambda is null.</returns>
public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection)
{
return input.ValueOrDefault(projection, default(TOut));
}
The overload not taking a specific default value will return null for any reference type. This should work in your scenario:
class test
{
private test()
{
var person = new Person();
if (person.ValueOrDefault(p=>p.contact.address.city) != null)
{
//the above will return null without exception if any member in the chain is null
}
}
}
Such a reference chain may occurre for example if you use an ORM tool, and want to keep your classes as pure as possible. In this scenario I think it cannot be avoided nicely.
I have the following extension method "family", which checks if the object on which it's called is null, and if not, returns one of it's requested properties, or executes some methods with it. This works of course only for reference types, that's why I have the corresponding generic constraint.
public static TRet NullOr<T, TRet>(this T obj, Func<T, TRet> getter) where T : class
{
return obj != null ? getter(obj) : default(TRet);
}
public static void NullOrDo<T>(this T obj, Action<T> action) where T : class
{
if (obj != null)
action(obj);
}
These methods add almost no overhead compared to the manual solution (no reflection, no expression trees), and you can achieve a nicer syntax with them (IMO).
var city = person.NullOr(e => e.Contact).NullOr(e => e.Address).NullOr(e => e.City);
if (city != null)
// do something...
Or with methods:
person.NullOrDo(p => p.GoToWork());
However, one could definetely argue about the length of code didn't change too much.
In my opinion, the equality operator is not a safer and better way for reference equality.
It's always better to use ReferenceEquals(obj, null). This will always work. On the other hand, the equality operator (==) could be overloaded and might be checking if the values are equal instead of the references, so I will say ReferenceEquals() is a safer and better way.
class MyClass {
static void Main() {
object o = null;
object p = null;
object q = new Object();
Console.WriteLine(Object.ReferenceEquals(o, p));
p = q;
Console.WriteLine(Object.ReferenceEquals(p, q));
Console.WriteLine(Object.ReferenceEquals(o, p));
}
}
Reference: MSDN article Object.ReferenceEquals Method.
But also here are my thoughts for null values
Generally, returning null values is the best idea if anyone is trying to indicate that there is no data.
If the object is not null, but empty, it implies that data has been returned, whereas returning null clearly indicates that nothing has been returned.
Also IMO, if you will return null, it will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code.
In C#, there are two different kinds of equality:
reference equality and
value equality.
When a type is immutable, overloading operator == to compare value equality instead of reference equality can be useful.
Overriding operator == in non-immutable types is not recommended.
Refer to the MSDN article Guidelines for Overloading Equals() and Operator == (C# Programming Guide) for more details.
As much as I love C#, this is one thing that's kind of likable about C++ when working directly with object instances; some declarations simply cannot be null, so there's no need to check for null.
The best way you can get a slice of this pie in C# (which might be a bit too much redesigning on your part - in which case, take your pick of the other answers) is with struct's. While you could find yourself in a situation where a struct has uninstantiated "default" values (ie, 0, 0.0, null string) there's never a need to check "if (myStruct == null)".
I wouldn't switch over to them without understanding their use, of course. They tend to be used for value types, and not really for large blocks of data - anytime you assign a struct from one variable to another, you tend to be actually copying the data across, essentially creating a copy of each of the original's values (you can avoid this with the ref keyword - again, read up on it rather than just using it). Still, it may fit for things like StreetAddress - I certainly wouldn't lazily use it on anything I didn't want to null-check.
Depending on what the purpose of using the "city" variable is, a cleaner way could be to separate the null checks into different classes. That way you also wouldn't be violating the Law of Demeter. So instead of:
if (person != null && person.contact != null && person.contact.address != null && person.contact.address.city != null)
{
// do some stuff here..
}
You'd have:
class test
{
private test()
{
var person = new Person();
if (person != null)
{
person.doSomething();
}
}
}
...
/* Person class */
doSomething()
{
if (contact != null)
{
contact.doSomething();
}
}
...
/* Contact class */
doSomething()
{
if (address != null)
{
address.doSomething();
}
}
...
/* Address class */
doSomething()
{
if (city != null)
{
// do something with city
}
}
Again, it depends on the purpose of the program.
In what circumstances can those things be null? If nulls would indicate a bug in the code then you could use code contracts. They will pick it up if you get nulls during testing, then will go away in the production version. Something like this:
using System.Diagnostics.Contracts;
[ContractClass(typeof(IContactContract))]
interface IContact
{
IAddress address { get; set; }
}
[ContractClassFor(typeof(IContact))]
internal abstract class IContactContract: IContact
{
IAddress address
{
get
{
Contract.Ensures(Contract.Result<IAddress>() != null);
return default(IAddress); // dummy return
}
}
}
[ContractClass(typeof(IAddressContract))]
interface IAddress
{
string city { get; set; }
}
[ContractClassFor(typeof(IAddress))]
internal abstract class IAddressContract: IAddress
{
string city
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string); // dummy return
}
}
}
class Person
{
[ContractInvariantMethod]
protected void ObjectInvariant()
{
Contract.Invariant(contact != null);
}
public IContact contact { get; set; }
}
class test
{
private test()
{
var person = new Person();
Contract.Assert(person != null);
if (person.contact.address.city != null)
{
// If you get here, person cannot be null, person.contact cannot be null
// person.contact.address cannot be null and person.contact.address.city cannot be null.
}
}
}
Of course, if the possible nulls are coming from somewhere else then you'll need to have already conditioned the data. And if any of the nulls are valid then you shouldn't make non-null a part of the contract, you need to test for them and handle them appropriately.
One way to remove null checks in methods is to encapsulate their functionality elsewhere. One way to do this is through getters and setters. For instance, instead of doing this:
class Person : IPerson
{
public IContact contact { get; set; }
}
Do this:
class Person : IPerson
{
public IContact contact
{
get
{
// This initializes the property if it is null.
// That way, anytime you access the property "contact" in your code,
// it will check to see if it is null and initialize if needed.
if(_contact == null)
{
_contact = new Contact();
}
return _contact;
}
set
{
_contact = value;
}
}
private IContact _contact;
}
Then, whenever you call "person.contact", the code in the "get" method will run, thus initializing the value if it is null.
You could apply this exact same methodology to all of the properties that could be null across all of your types. The benefits to this approach are that it 1) prevents you from having to do null checks in-line and it 2) makes your code more readable and less prone to copy-paste errors.
It should be noted, however, that if you find yourself in a situation where you need to perform some action if one of the properties is null (i.e. does a Person with a null Contact actually mean something in your domain?), then this approach will be a hindrance rather than a help. However, if the properties in question should never be null, then this approach will give you a very clean way of representing that fact.
--jtlovetteiii
You could use reflection, to avoid forcing implementation of interfaces and extra code in every class. Simply a Helper class with static method(s). This might not be the most efficient way, be gentle with me, I'm a virgin (read, noob)..
public class Helper
{
public static bool IsNull(object o, params string[] prop)
{
if (o == null)
return true;
var v = o;
foreach (string s in prop)
{
PropertyInfo pi = v.GetType().GetProperty(s); //Set flags if not only public props
v = (pi != null)? pi.GetValue(v, null) : null;
if (v == null)
return true;
}
return false;
}
}
//In use
isNull = Helper.IsNull(p, "ContactPerson", "TheCity");
Offcourse if you have a typo in the propnames, the result will be wrong (most likely)..

Conditional typing in generic method

Consider the following (heavily simplified) code:
public T Function<T>() {
if (typeof(T) == typeof(string)) {
return (T) (object) "hello";
}
...
}
It's kind of absurd to first cast to object, then to T. But the compiler has no way of knowing that the previous test assured T is of type string.
What is the most elegant, idiomatic way of achieving this behavior in C# (which includes getting rid of the stupid typeof(T) == typeof(string), since T is string can't be used)?
Addendum: There is no return type variance in .net, so you can't make a function overload to type string (which, by the way, is just an example, but one reason why association end redefinition in polymorphism, e.g. UML, can't be done in c#). Obviously, the following would be great, but it doesn't work:
public T Function<T>() {
...
}
public string Function<string>() {
return "hello";
}
Concrete Example 1: Because there's been several attacks to the fact that a generic function that tests for specific types isn't generic, I'll try to provide a more complete example. Consider the Type-Square design pattern. Here follows a snippet:
public class Entity {
Dictionary<PropertyType, object> properties;
public T GetTypedProperty<T>(PropertyType p) {
var val = properties[p];
if (typeof(T) == typeof(string) {
(T) (object) p.ToString(this); // magic going here
}
return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(val);
}
}
Concrete Example 2: Consider the Interpreter design pattern:
public class Expression {
public virtual object Execute() { }
}
public class StringExpression: Expression {
public override string Execute() { } // Error! Type variance not allowed...
}
Now let's use generics in Execute to allow the caller to force a return type:
public class Expression {
public virtual T Execute<T>() {
if(typeof(T) == typeof(string)) { // what happens when I want a string result from a non-string expression?
return (T) (object) do_some_magic_and_return_a_string();
} else if(typeof(T) == typeof(bool)) { // what about bools? any number != 0 should be True. Non-empty lists should be True. Not null should be True
return (T) (object) do_some_magic_and_return_a_bool();
}
}
}
public class StringExpression: Expressiong {
public override T Execute<T>() where T: string {
return (T) string_result;
}
}
If you're making these types of checks in a generic method, I'd rethink your design. The method is obviously not truly generic - if it were, you wouldn't need specific type checking...
Situations like this typically can be handled more cleanly by a redesign. One alternative is often to provide an overload of the appropriate type. Other design alternatives which avoid the type-specific behavior exist, as well, such as Richard Berg's suggestion of passing in a delegate.
using System;
using System.Collections.Generic;
using System.Linq;
namespace SimpleExamples
{
/// <summary>
/// Compiled but not run. Copypasta at your own risk!
/// </summary>
public class Tester
{
public static void Main(string[] args)
{
// Contrived example #1: pushing type-specific functionality up the call stack
var strResult = Example1.Calculate<string>("hello", s => "Could not calculate " + s);
var intResult = Example1.Calculate<int>(1234, i => -1);
// Contrived example #2: overriding default behavior with an alternative that's optimized for a certain type
var list1 = new List<int> { 1, 2, 3 };
var list2 = new int[] { 4, 5, 6 };
Example2<int>.DoSomething(list1, list2);
var list1H = new HashSet<int> { 1, 2, 3 };
Example2<int>.DoSomething<HashSet<int>>(list1H, list2, (l1, l2) => l1.UnionWith(l2));
}
}
public static class Example1
{
public static TParam Calculate<TParam>(TParam param, Func<TParam, TParam> errorMessage)
{
bool success;
var result = CalculateInternal<TParam>(param, out success);
if (success)
return result;
else
return errorMessage(param);
}
private static TParam CalculateInternal<TParam>(TParam param, out bool success)
{
throw new NotImplementedException();
}
}
public static class Example2<T>
{
public static void DoSomething(ICollection<T> list1, IEnumerable<T> list2)
{
Action<ICollection<T>, IEnumerable<T>> genericUnion = (l1, l2) =>
{
foreach (var item in l2)
{
l1.Add(item);
}
l1 = l1.Distinct().ToList();
};
DoSomething<ICollection<T>>(list1, list2, genericUnion);
}
public static void DoSomething<TList>(TList list1, IEnumerable<T> list2, Action<TList, IEnumerable<T>> specializedUnion)
where TList : ICollection<T>
{
/* stuff happens */
specializedUnion(list1, list2);
/* other stuff happens */
}
}
}
/// I confess I don't completely understand what your code was trying to do, here's my best shot
namespace TypeSquarePattern
{
public enum Property
{
A,
B,
C,
}
public class Entity
{
Dictionary<Property, object> properties;
Dictionary<Property, Type> propertyTypes;
public T GetTypedProperty<T>(Property p)
{
var val = properties[p];
var type = propertyTypes[p];
// invoke the cast operator [including user defined casts] between whatever val was stored as, and the appropriate type as
// determined by the domain model [represented here as a simple Dictionary; actual implementation is probably more complex]
val = Convert.ChangeType(val, type);
// now create a strongly-typed object that matches what the caller wanted
return (T)val;
}
}
}
/// Solving this one is a straightforward application of the deferred-execution patterns I demonstrated earlier
namespace InterpreterPattern
{
public class Expression<TResult>
{
protected TResult _value;
private Func<TResult, bool> _tester;
private TResult _fallback;
protected Expression(Func<TResult, bool> tester, TResult fallback)
{
_tester = tester;
_fallback = fallback;
}
public TResult Execute()
{
if (_tester(_value))
return _value;
else
return _fallback;
}
}
public class StringExpression : Expression<string>
{
public StringExpression()
: base(s => string.IsNullOrEmpty(s), "something else")
{ }
}
public class Tuple3Expression<T> : Expression<IList<T>>
{
public Tuple3Expression()
: base(t => t != null && t.Count == 3, new List<T> { default(T), default(T), default(T) })
{ }
}
}
Can you use as here?
T s = "hello" as T;
if(s != null)
return s;
I can't think of an "elegant" way to do this. As you say, the compiler can't know that the conditional has ensured that the type of T is string. As a result, it has to assume that, since there's no generalized way to convert from string to T, it's an error. object to T might succeed, so the compiler allows it.
I'm not sure I'd want an elegant way to express this. Although I can see where it'd be necessary to do explicit type checks like this in some situations, I think I'd want it to be cumbersome because it really is a bit of a hack. And I'd want it to stick out: "Hey! I'm doing something weird here!"
Ok, I took a run at it from several different angles and came up short. I would have to conclude that if your current implementation gets the job done you should take the win and move on. Short of some arcane emissions what you got is what you get.
But the compiler has no way of knowing
that the previous test assured T is of
type string.
Umm.... If I am not mistaken, generics is just code gen. The compiler generates a matching method for each distinct type found in the calling methods. So the compiler does know the type argument for the overload being called. Again; If I am not mistaken.
But overall, i think you are misusing the generic in this case, from what I can see, and as others have stated, there are more appropriate solutions..... which are unnamable unless you post code that completely specifies your requirements.
just my 2 pesos...

generic function with a "has property X" constraint?

I have a third-party, closed source application that exports a COM interface, which I am using in my C#.NET application through Interop. This COM interface exports many objects that all show up as System.Object until I cast them to the appropriate interface type. I want to assign an property of all of these objects. Thus:
foreach (object x in BigComInterface.Chickens)
{
(x as Chicken).attribute = value;
}
foreach (object x in BigComInterface.Ducks)
{
(x as Duck).attribute = value;
}
But assigning the property is likely (for application-specific reasons that are unavoidable) to throw Exceptions from which I want to recover, so I really want a try/catch around each one. Thus:
foreach (object x in BigComInterface.Chickens)
{
try
{
(x as Chicken).attribute = value;
}
catch (Exception ex)
{
// handle...
}
}
foreach (object x in BigComInterface.Ducks)
{
try
{
(x as Duck).attribute = value;
}
catch (Exception ex)
{
// handle...
}
}
Obviously, it would be so much cleaner to do this:
foreach (object x in BigComInterface.Chickens)
{
SetAttribute<Chicken>(x as Chicken, value);
}
foreach (object x in BigComInterface.Ducks)
{
SetAttribute<Duck>(x as Duck, value);
}
void SetAttribute<T>(T x, System.Object value)
{
try
{
x.attribute = value;
}
catch
{
// handle...
}
}
See the problem? My x value can be of any type, so the compiler can't resolve .attribute. Chicken and Duck are not in any kind of inheritance tree and they do not share an interface that has .attribute. If they did, I could put a constraint for that interface on T. But since the class is closed-source, that's not possible for me.
What I want, in my fantasy, is something like a constraint requiring the argument to have the .attribute property regardless of whether it implements a given interface. To wit,
void SetAttribute<T>(T x, System.Object value) where T:hasproperty(attribute)
I'm not sure what to do from here other than to cut/paste this little try/catch block for each of Chicken, Duck, Cow, Sheep, and so on.
My question is: What is a good workaround for this problem of wanting to invoke a specific property on an object when the interface that implements that property cannot be known at compile time?
Well, depending on how humongous your exception handling code is (and if i am not mistaken it could be quite so) using the following trick might help you:
class Chicken
{
public string attribute { get; set; }
}
class Duck
{
public string attribute { get; set; }
}
interface IHasAttribute
{
string attribute { get; set; }
}
class ChickenWrapper : IHasAttribute
{
private Chicken chick = null;
public string attribute
{
get { return chick.attribute; }
set { chick.attribute = value; }
}
public ChickenWrapper(object chick)
{
this.chick = chick as Chicken;
}
}
class DuckWrapper : IHasAttribute
{
private Duck duck = null;
public string attribute
{
get { return duck.attribute; }
set { duck.attribute = value; }
}
public DuckWrapper(object duck)
{
this.duck = duck as Duck;
}
}
void SetAttribute<T>(T x, string value) where T : IHasAttribute
{
try
{
x.attribute = value;
}
catch
{
// handle...
}
}
Unfortunately, this is tricky currently. In C# 4, the dynamic type may help quite a bit with this. COM interop is one of the places that dynamic really shines.
However, in the meantime, the only option that allows you to have any type of object, with no restrictions on interfaces, would be to revert to using reflection.
You can use reflection to find the "attribute" property, and set it's value at runtime.
To not have to violate the DRY principle you can use reflection. If you really want to use generics, you could use a wrapper class for each type of 3rd party object and have the wrapper implement an interface that you can use to constrain the generic type argument.
An example of how it could be done with reflection. Code is not tested though.
void SetAttribute(object chickenDuckOrWhatever, string attributeName, string value)
{
var typeOfObject = chickenDuckOrWhatever.GetType();
var property = typeOfObject.GetProperty(attributeName);
if (property != null)
{
property.SetValue(chickenDuckOrWhatever, value);
return;
}
//No property with this name was found, fall back to field
var field = typeOfObject.GetField(attributeName);
if (field == null) throw new Exception("No property or field was found on type '" + typeOfObject.FullName + "' by the name of '" + attributeName + "'.");
field.SetValue(chickenDuckOrWhatever, value);
}
If you to speed up the code for performance, you could cache the FieldInfo and PropertyInfo per type of chickenDuckOrWhatever and consult the dictionary first before reflecting.
TIP: To not have to hardcode the attributeName as a string, you could use C# 6 feature nameof. Like nameof(Chicken.AttributeName) for example.
Unfortunately the only way to do this is to constrain the type parameter with an interface that defines that property and is implemented on all types.
Since you do not have the source this will be impossible to implement and as such you will have to use some sort of workaround. C# is statically typed and as such doesn't support the kind of duck-typing you want to use here. The best thing coming soon (in C# 4) would be to type the object as dynamic and resolve the property calls at execution time (note that this approach would also not be generic as you cannot constrain a generic type parameter as dynamic).

Fallback accessors in C#?

Does C# have anything like Python's __getattr__?
I have a class with many properties, and they all share the same accessor code. I would like to be able to drop the individual accessors entirely, just like in Python.
Here's what my code looks like now:
class Foo
{
protected bool Get(string name, bool def)
{
try {
return client.Get(name);
} catch {
return def;
}
}
public bool Bar
{
get { return Get("bar", true); }
set { client.Set("bar", value); }
}
public bool Baz
{
get { return Get("baz", false); }
set { client.Set("baz", value); }
}
}
And here's what I'd like:
class Foo
{
public bool Get(string name)
{
try {
return client.Get(name);
} catch {
// Look-up default value in hash table and return it
}
}
public void Set(string name, object value)
{
client.Set(name, value)
}
}
Is there any way to achieve this in C# without calling Get directly?
Thanks,
No. Although C# supports reflection, it is read-only (for loaded assemblies). That means you can't change any methods, properties, or any other metadata. Although you could create a dynamic property, calling it wouldn't be very convenient - it would be even worse than using your Get method. Aside from using a Dictionary<string, object> and an indexer for your class, there's not much else you can do. Anyway, isn't doing a dictionary better if you have that many properties?
Python doesn't check if an attribute exists at "compile-time" (or at least load-time). C# does. That's a fundamental difference between the two languages. In Python you can do:
class my_class:
pass
my_instance = my_class()
my_instance.my_attr = 1
print(my_instance.my_attr)
In C# you wouldn't be able to do that because C# actually checks if the name my_attr exists at compile-time.
I'm not sure, but perhaps the dynamic features of version 4.0 will help you with that. You'll have to wait though...
Can I ask: why don't you want the individual properties? That is the idiomatic .NET way of expressing the data associated with an object.
Personally, assuming the data isn't sparse, I would keep the properties and have the overall method use reflection - this will make your compiled code as fast as possible:
protected T Get<T>(string name, T #default)
{
var prop = GetType().GetProperty(name);
if(prop == null) return #default;
return (T) prop.GetValue(this, null);
}
Of course, if you don't care about the properties themselves being defined, then an indexer and lookup (such as dictionary) would be OK. There are also things you might be able to do with postsharp to turn a set of properties into a property-bag - probably not worth it, though.
If you want the properties available for data-binding and runtime discovery, but can't define them at compile-time, then you would need to look at dynamic type descriptors; either ICustomTypeDescriptor or TypeDescriptionProvider - a fair bit of work, but very versatile (let me know if you want more info).
This is not the same as what you get in Python with dynamic property names, but you might find it useful:
using System;
using System.Collections.Generic;
namespace Program
{
class Program
{
static void Main(string[] args)
{
MyList<int> list = new MyList<int>();
// Add a property with setter.
list["One"] = 1;
// Add a property with getter which takes default value.
int two = list["Two", 2];
Console.WriteLine("One={0}", list["One"]);
Console.WriteLine("Two={0} / {1}", two, list["Two"]);
try
{
Console.WriteLine("Three={0}", list["Three"]);
}
catch
{
Console.WriteLine("Three does not exist.");
}
}
class MyList<T>
{
Dictionary<string, T> dictionary = new Dictionary<string,T>();
internal T this[string property, T def]
{
get
{
T value;
if (!dictionary.TryGetValue(property, out value))
dictionary.Add(property, value = def);
return value;
}
}
internal T this[string property]
{
get
{
return dictionary[property];
}
set
{
dictionary[property] = value;
}
}
}
}
}

Categories

Resources