Archive

Posts Tagged ‘.net’

Implicit and Explicit Implementation of Interface

January 26, 2011 Leave a comment

Difference Between Explicit and Implicit Implementation

Usually we implement interfaces implicitly. This has an advantage when we need to call method defined in interface: it can be called from variable either of type interface or class. In the same time explicitly implemented method cannot be called from variable of type class.

This is demonstrated by the code below:

namespace ExplicitInterfaceImplementation
{
    class Program
    {
        static void Main(string[] args)
        {
            Sample sampleObject = new Sample();

            CallExplicitlyImplementedMethod(sampleObject);
            CallImlicitlyImplementedMethod(sampleObject);

            Console.ReadLine();
        }

        static void CallExplicitlyImplementedMethod(Sample sampleObject)
        {
            // When uncommented next line will not compile.
            //sampleObject.ExplicitMethod();

            // This is how we can call explicitely implemented method.
            ISample sampleInterface = sampleObject as ISample;
            sampleInterface.ExplicitMethod();
        }

        static void CallImlicitlyImplementedMethod(Sample sampleObject)
        {
            // Next line will compile and execute without problems.
            sampleObject.ImplicitMethod();

            // Also we can call implicitely implemented method using interface.
            ISample sampleInterface = sampleObject as ISample;
            sampleInterface.ImplicitMethod();
        }
    }

    interface ISample
    {
        void ExplicitMethod();
        void ImplicitMethod();
    }

    class Sample : ISample
    {
        void ISample.ExplicitMethod()
        {
            Console.WriteLine("ExplicitMethod()");
        }

        public void ImplicitMethod()
        {
            Console.WriteLine("ImplicitMethod()");
        }
    }
}

One more important thing is that explicitly implemented method always public. For this reason C# doesn’t allow to use access modifier for the method.

Why Could We Need Explicit Implementation?

So explicit implementation narrows usage of the method. When can we have advantage of it in this case?

It is useful when implementing two interfaces containing methods with the same signature as shown in sample below:

namespace ExplicitInterfaceImplementationUsage
{
    class Program
    {
        static void Main(string[] args)
        {
            Operations operations = new Operations();

            IAddition addition = operations as IAddition;
            ISubtraction subtraction = operations as ISubtraction;

            Console.WriteLine(addition.Compute(1, 1));
            Console.WriteLine(subtraction.Compute(1, 1));

            Console.ReadLine();
        }
    }

    interface IAddition
    {
        int Compute(int left, int right);
    }
    interface ISubtraction
    {
        int Compute(int left, int right);
    }

    class Operations : IAddition, ISubtraction
    {
        int IAddition.Compute(int left, int right)
        {
            return left + right;
        }

        int ISubtraction.Compute(int left, int right)
        {
            return left - right;
        }
    }
}

Actually we could implement Compute() method implicitly from one interface and explicitly from another one. Nevertheless I wouldn’t recommend such solution because it will be even harder for client code to decide how to call Compute() method correctly.

I must confess I never had to use explicit interface implementation. So samples here are fake ones.

Did you have to use it in production code? Was it something else then you couldn’t change method name in interfaces because its in third-party library?

Categories: Sharp C# Tags:

How To: Read String Line by Line

January 19, 2011 Leave a comment

Breaking a string containing multi-line text to a list of lines can be easily done using StringReader. Here is a method that does this and small test program:


class Program
{
    static void Main(string[] args)
    {
        IList<string> lines = BreakLines("This is a test for breaking multiline string \nto a list of lines.");

        foreach (var item in lines)
        {
            Console.WriteLine(item);
        }

        Console.ReadLine();
    }

    private static IList<string> BreakLines(string text)
    {
        IList<string> lines = new List<string>();

        using (StringReader reader = new StringReader(text))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }

        return lines;
    }
}

 

Categories: Development, How To Tags: ,

“throw;” vs “throw ex;”

December 28, 2010 Leave a comment

Sometimes exception gets caught to make some logging and rethrow it upper (i.e. log exception in library and then throw it to client code).

In this case it’s important to understand that “throw ex;” will cut stack trace. So when caught in calling code exception will contain StackTrace and TargetSite starting from the method that rethrown it. Sometimes it’s desirable to hide real stack trace, sometimes – not.

Lets take a look at following code:

class Program
{
       static void Main(string[] args)
       {
              Program p = new Program();
              p.ClientMethod();

              Console.ReadLine();
       }

       void ClientMethod()
       {
              try
              {
                     LibraryAPI();
              }
               catch (Exception ex)
              {
                      Console.WriteLine(ex.StackTrace);
              }
       }

       void LibraryAPI()
       {
              try
              {
                     LibraryInternal();
              }
               catch (Exception ex)
              {
                      throw ex;
              }
       }

       void LibraryInternal()
       {
               throw new Exception("Trace me if you can");
       }
}

Although exception was thrown in LibraryInternal() method console output will be following:
at ConsoleApplication6.Program.LibraryAPI() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 35
at ConsoleApplication6.Program.ClientMethod() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 19

By changing “throw ex;” to “throw;” in LibraryAPI() stack trace in console output will change to:
at ConsoleApplication6.Program.LibraryInternal() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 41
at ConsoleApplication6.Program.LibraryAPI() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 35
at ConsoleApplication6.Program.ClientMethod() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 19

This difference in behavior has simple explanation: MSIL has two instructions “throw” and “rethrow” while C# has only one keyword “throw”. When code gets compiled all “throw;” lines end up with “rethrow” in MSIL which will keep original stack trace.

Categories: Sharp C# Tags:

Virtual Functions in Constructors Trap

May 5, 2010 Leave a comment

In .NET calling virtual function in constructor of a class is a bit tricky. While one can expect that implementation from current class will be invoked, runtime actually always calls implementation of the function from the most derived class of all possible. So if virtual method in child class doesn’t call implementation from parent one can get trapped and initialization will be done incorrect.

For example, using BaseClass and DerivedClass provided below

		class BaseClass {
			public string DefaultName {
				get {
					return _defaultName;
				}
			}
			protected string _defaultName;

			public BaseClass() {
				InitializeDefaults();
			}

			public virtual void InitializeDefaults() {
				_defaultName = "BaseClass";
			}
		}

		class DerivedClass : BaseClass {
			public DerivedClass() {
			}

			public override void InitializeDefaults() {
			}
		}

when creating instances of the classes DefaultName will be different:
BaseClass baseClass = new BaseClass();
// baseClass.DefaultName: "BaseClass"

DerivedClass derivedClass = new DerivedClass();
// derivedClass.DefaultName: null

Categories: Development, Sharp C# Tags:

The Most Unexpected Explanation of Delegates I’ve Ever Read

January 29, 2009 Leave a comment

Once upon a time, in a strange land south of here, there was a worker named Peter. He was a diligent worker who would readily accept requests from his boss. However, his boss was a mean, untrusting man who insisted on steady progress reports. Since Peter did not want his boss standing in his office looking over his shoulder, Peter promised to notify his boss whenever his work progressed.

To read full story follow the link .NET Delegates: A C# Bedtime Story.

Categories: Development Tags:
Follow

Get every new post delivered to your Inbox.