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"; }
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With