Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a library that I'm using that has the following interface:
C#
public interface IStringType
{
    string GetValue();
    bool IsSet();
    void SetValue(string val);
}

So, when I go to use this, I need to do checks like so:
C#
public void ReadName(IStringType i)
{
    string Name;

    if(i != null)
    {
        Name = i.GetValue();
    }
    else
    {
        Name = string.Empty;
    }
}

Ideally, I'd like to just be able to do this:
C#
public void ReadName(IStringType i)
{
    string Name = i;
}

I found some information on doing implicit conversions, but it seems like it more geared for when you are creating your own interfaces/classes, not trying to use others existing ones.
Posted
Comments
PIEBALDconsult 21-Mar-14 15:08pm    
For that particular example you might want to try the ?? operator.

string Name = i ?? string.Empty ;
OriginalGriff 21-Mar-14 15:34pm    
Except...that doesn't work, because string is not derived from IStringType.
The compiler will complain.
PIEBALDconsult 21-Mar-14 16:00pm    
Yes, but eliminate the Interface; it's a false-start.
Sergey Alexandrovich Kryukov 21-Mar-14 16:45pm    
It makes no sense at all. If you explained you ultimate purpose, you could get some practical advice.
—SA
hpjchobbes 21-Mar-14 18:34pm    
It's really just trying to simplify using a third party library. It's the QuickBooks SDK, and they do this with almost all their types; IQBStringType, IQBAmountType, IQBAddress, etc. I end up coding a lot of "if( i != null)" checks before I can use anything, and it just feels like redundant code.

1 solution

Trouble is that you can't implement any code in an interface, so you can't create a implicit cast operator!

There is no real solution: Except to declare a "dummy" derived class or a static instance of a derived class that is empty:
C#
public interface IStringType
    {
    string GetValue();
    bool IsSet();
    void SetValue(string val);
    }
public class ConcreteStringType : IStringType
    {
    public string GetValue() { return string.Empty; }
    }
public void ReadName(IStringType i)
    {
    string Name = (i ?? new ConcreteStringType()).GetValue();
    }

Or
C#
public interface IStringType
    {
    string GetValue();
    bool IsSet();
    void SetValue(string val);
    }
public class DerivedStringType : IStringType
    {
    }
public static DerivedStringType inst = new DerivedStringType();
public void ReadName(IStringType i)
    {
    string Name = (i ?? inst).GetValue();
    }

Nasty...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900