Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Interface to create Optional property

Tags:

c#

interface

I have Interface written in C# and is it already implemented by classes. Is it possible can i add one more property as optional in interface and without modifying the exiting implemented classes?

E.g

public interface IShape
{
    int area { get; }
}

public class FindWindow : IShape
{
    public int area
    {
        get
        {
            return 10;
        }
    }
}

In this FindWindow is already written. Is it possible can i add one Optional Property and not implementing in the existing class.

ie,

public interface IShape
{
    int area { get; }
    //optional
    //string WindowName{get;}
}

public class FindWindow : IShape
{
    public int area
    {
        get
        {
            return 10;
        }
    }

    //WindowName i am not implementing here
}

public class FindWindowName : IShape
{
    public int area
    {
        get { return 20; }
    }

    public string WindowName
    {
        get { return "Stack Overflow"; }
    }
}
like image 857
Britto Raj Avatar asked Jul 25 '13 10:07

Britto Raj


1 Answers

There's no concept of optional members of an interface.

What you need here is to define two interfaces. One contains area, and the other contains WindowName. Something like this:

public interface IShape
{
    int area { get; }
}

public interface IFindWindow: IShape
{
    string WindowName { get; }
}

Then the implementing classes can choose to implement either IShape or IFindWindow.

At runtime you simply use the is operator to determine whether or not IFindWindow is implemented by the object at hand.

IShape shape = ...;
if (shape is IFindWindow)
    ....

And to actually use the more derived interface use the as operator:

IShape shape = ...;
IFindWindow findWindow = shape as IFindWindow;
if (findWindow != null)
    string windowName = findWindow.WindowName;
like image 50
David Heffernan Avatar answered Sep 29 '22 02:09

David Heffernan