Safe & Simple Access to Explicit Interface Members in C?

Here is a compile-time checked one liner: public static class Converter { public static T ReturnAs(T item) { return item; } } class Program { static void Main(string args) { var item = new MyType(); // Option 1 - Implicit cast. Compile time checked but takes two lines. IMyType item2 = item; System.Console.

WriteLine(item2. Say // Option 2 - One line but risks an InvalidCastException at runtime if MyType changes. System.Console.

WriteLine(((IMyType)item). Say // Option 3 - One line but risks a NullReferenceException at runtime if MyType changes.System.Console. WriteLine((item as IMyType).

Say // Option 4 - compile time one liner Converter. ReturnAs(item).Say.

Good point. This works even better with extension methods. – Joseph Sturtevant May 21 '10 at 22:13.

As an answer to all three questions: Rely on implicit casts as a general rule. You're programming against the interface, not the implementation. As for the last one, if you really must rely on programming against an implementation (a specific derived class) then make sure the object can be cast the type before attempting to do anything with it.

Something like this: var IMyType item3 = item as MyConcreteType; if(item3! = null) { item3.Say.

1 I agree with relying on implicit casts as a general rule. It is more elegant in my opinion. – Carlos Loth May 21 '10 at 6:16.

If you're not sure that the object is an instance of the interface then do an as/null check. Usually you're returning an interface from a method/function call in which case you just store it in a variable without a cast (though the null check may still be necessary).

I usually like it as: class Program { static void Main(string args) { var item = new MyType(); if( item is IMyType ){ Console. WriteLine( (item as IMyType). Say } else { /* Do something here... */ } } }.

2 you are applying the cast twice unnecessarily. You should do the "as" first and then simply do a null check. – Brian Rudolph May 20 '10 at 18:38.

This is due to the nature of the interface. An interface, by definition is a specification. A rule in .

NET specifications dictates that a class that implements an interface will have to implement all members of that interface. Now if we mark a member private, then the implementing class cannot implement that particular member.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions