I have currently a problem
I have 1 Interface with two types of argument like this
ITestInterface<ArgumentA>
ITestInterface<ArgumentB>
this interface has only the argument as different
I would like to pass this interface to an constructor of a class. sth like this
public class MyClass
{
public ITestInterface<object> MyInterface {get; set;}
public MyClass(ITestInterface<ArgumentA> testInterfaceA){
this.MyInterface = testInterfaceA as ITestInterface<object>;
this.MyTestInterface.SomeEvent += this.OnSubcribe;
}
public MyClass(ITestInterface<ArgumentB> testInterfaceB){
this.MyInterface = testInterfaceB as ITestInterface<object>;
this.MyTestInterface.SomeEvent += this.OnSubcribe;
}
public void OnSubcribe(){
//Work to do here, dont care about what argument the interface has.
}
}
and to call the MyClass constructor I have sth like this:
public List<MyClass> ClassList = new();
public void testMethod(){
var interA = getInterfaceWithArgumentA();
var myClassA = new MyClass(interA);
var interB = getInterfaceWithArgumentB();
var myClassB = new MyClass(interB);
}
So the problem is i am not able to cast the interface argument to object. I dont need to differenciate the argument either. I just want to avoid to have 2 properties of MyInterface like (MyInterfaceA, MyInterfaceB).
I need also to consider that maybe in the future I will have more type of Argument so maybe to have multiple properties like MyInterfaceA, MyInterfaceB, MyInterfaceC and also multiple constructor for each Interfaceargument type would be a mess.
I just thought about have a Baseclass and the ArgumentA and ArgumentB class derived from it so the cast would work but its not like that.
How would I solve this problem ?
Many Thanks
I think you have not provided what getInterfaceWithArgumentB() and getInterfaceWithArgumentA() method doing. I am making few assumption.
To solve your problem Generic will help.
Following is the example of it.
public class MyClass<T>
{
public ITestInterface<T> MyInterface { get; set; }
public MyClass(ITestInterface<T> testInterfaceA)
{
this.MyInterface = testInterfaceA;
this.MyInterface.SomeEvent += MyInterface_SomeEvent;
}
private void MyInterface_SomeEvent(object sender, EventArgs e)
{
Console.WriteLine(sender);
}
}
public class ArgumentA
{
public string Name { get; set; }
}
public class ArgumentB
{
public int Id { get; set; }
}
public interface ITestInterface<T>
{
T Data { get; set; }
event EventHandler SomeEvent;
void OnSomeEvent();
}
public class TestInterface<T> : ITestInterface<T>
{
public T Data { get ; set; }
public event EventHandler SomeEvent;
public void OnSomeEvent()
{
if(SomeEvent != null)
SomeEvent(Data, EventArgs.Empty);
}
}
You can use it like following.
MyClass<ArgumentA> myClass = new MyClass<ArgumentA>(
new TestInterface<ArgumentA>()
{
Data = new ArgumentA() { Name = "test" }
});
MyClass<ArgumentB> myClas2 = new MyClass<ArgumentB>(
new TestInterface<ArgumentB>()
{
Data = new ArgumentB() { Id = 10 }
});
myClas2.MyInterface.OnSomeEvent();
myClass.MyInterface.OnSomeEvent();
UPDATE
class Program
{
static void Main(string[] args)
{
ObservableCollection<MyClass> items = new ObservableCollection<MyClass>();
MyClass<ArgumentA> myClass = new MyClass<ArgumentA>(
new TestInterface<ArgumentA>()
{
Data = new ArgumentA() { Name = "test" }
});
MyClass<ArgumentB> myClas2 = new MyClass<ArgumentB>(
new TestInterface<ArgumentB>()
{
Data = new ArgumentB() { Id = 10 }
});
items.Add(myClass);
items.Add(myClas2);
myClas2.MyInterface.OnSomeEvent();
myClass.MyInterface.OnSomeEvent();
}
}
public class MyClass
{
public ITestInterface MyInterface { get; set; }
}
public class MyClass<T> : MyClass
{
public MyClass(ITestInterface<T> testInterfaceA)
{
this.MyInterface = testInterfaceA;
this.MyInterface.SomeEvent += MyInterface_SomeEvent;
}
private void MyInterface_SomeEvent(object sender, EventArgs e)
{
Console.WriteLine(sender);
}
}
public class ArgumentA
{
public string Name { get; set; }
}
public class ArgumentB
{
public int Id { get; set; }
}
public interface ITestInterface
{
event EventHandler SomeEvent;
void OnSomeEvent();
}
public interface ITestInterface<T> : ITestInterface
{
T Data { get; }
}
public class TestInterface<T> : ITestInterface<T>
{
public T Data { get; set; }
public event EventHandler SomeEvent;
public void OnSomeEvent()
{
if (SomeEvent != null)
SomeEvent(Data, EventArgs.Empty);
}
}
I have an interface defined like this:
public interface ISomeOrderService
{
T GetUserNameandPass<T>();
Task<IEnumerable<T>> FetchOrdersAsync<T>(bool useProxy, bool impersonateProxyUser);
}
For the GetUserNameandPass, I want it to return the following object in the implementing class:
public class NameandPass
{
public string UserName { get; set; }
public string Password { get; set; }
}
On the other hand, for the FetchOrdersAsync, I want it to return the following object in the implementing class:
public class SomeOrder
{
public string prop1 { get; set; }
public DateTime prop2 { get; set; }
internal static async Task<IEnumerable<SomeOrder>> ConvertServiceResponseToSomeOrderListAsync(SomeResponse someResponse)
{
//someResult
return someResult.ToList();
}
}
I have my implementing class that looks like this:
public class SomeOrderService : ISomeOrderService
{
private IAMSService _aMSService;
public SomeOrderService()
{
_aMSService = new AMSService();
}
public NameandPass GetUserNameandPass()
{
return _aMSService.GetProxyUser<NameandPass>("SomeTypeOfUser");
}
public async Task<IEnumerable<SomeOrder>> FetchOrdersAsync<SomeOrder>(bool useProxy, bool impersonateProxyUser)
{
//someResponse;
return await SomeOrder.ConvertServiceResponseToSomeOrderListAsync(someResponse);
}
}
Here I have this first error in line:
return await SomeOrder.ConvertServiceResponseToSomeOrderListAsync(someResponse);
SomeOrder is a type parameter, which is not valid in the given context.
And the other error comes in the AMSService:
public class AMSService : IAMSService
{
public NameandPass GetProxyUser<NameandPass>(string proxyUser)
{
//someProxyUserResultObject
return new NameandPass { UserName = someProxyUserResultObject.Username, Password = someProxyUserResultObject.Password };
}
}
Here I get this second error:
AMSService doesn't implement member 'IAMSService.GetProxyUser<T>(string)'. 'AMSService.GetProxyUser<NameandPass>(string)' cannot implement 'IAMSService.GetProxyUser<T>(string)' because it does not have matching return type of 'T'.'
The IAMSService.cs looks like this:
public interface IAMSService
{
T GetProxyUser<T>(string proxyUser);
}
What could I be doing wrong here? Is my Interface definition from the start not adequate?
Thank You for the help!
Here is my code below. It gives me Casting exception problem at selIngs.Add(da). tried with the 2nd way. it still give me the same exception. I wonder where I am doing wrong? Once I implement the interface or inherit the base class it should be ok to treat child class as the same. Any idea please?
//1st way
public interface IngredientInterface
{
double Concentration { get; set; }
string DateCreated { get; set; }
string DevCode { get; set; }
}
public class IngredientData : INotifyPropertyChanged, IngredientInterface
{
public string GroupCode
{
get { return groupCode; }
set
{
groupCode = value;
}
}
public double Setpoint { get; set; }
public bool IsHighlighted { get; set; }
public double PPT { get; set; }
}
public class FormulaUploadViewModelData: IngredientData
{
//.....
}
public class FormulaUploadViewModel :INotifyPropertyChanged
{
public FormulaUploadViewModel()
{
selIngs = new List<FormulaUploadViewModelData>();
}
private void IngsUp()
{
List<IngredientData> someIngData = new List<IngredientData>();
foreach (FormulaUploadViewModelData da in someIngData)
{
selIngs.Add(da); //here gives me casting exception
}
}
}
//2nd way
public class FormulaUploadViewModelData: IngredientInterface
{
//.....
}
public class FormulaUploadViewModel :INotifyPropertyChanged
{
public FormulaUploadViewModel()
{
selIngs = new List<FormulaUploadViewModelData>();
}
private void IngsUp()
{
List<IngredientInterface> someIngData = new List<IngredientInterface>();
foreach (FormulaUploadViewModelData da in someIngData)
{
selIngs.Add(da); //here gives me casting exception
}
}
}
All FormulaUploadViewModelData are IngredientInterface. So this will work:
var ingredients = new List<IngredientInterface>();
ingredients.Add(new FormulaUploadViewModelData());
But the opposite does not work because not all IngredientInterface are FormulaUploadViewModelData which is what should follow from allowing:
var formulas = new
List<FormulaUploadViewModelData>();
formulas(someIngredientInterface);
Solution? Make sure the da you are adding is in fact a FormulaUploadViewModelData. There is quite a few ways to do it, to name a couple:
Pattern matching
foreach (var da in someInData)
if (da is FormulaUploadViewModelData formula)
selIngs.Add(formula)
Use Enumerable.OfType<> extension method
foreach (var formula in
someInData.OfType<FormulaUploadViewModelData>())
selIngs.Add(formula)
Etc.
I am stuck on interfaces and inheritance. If I implement two classes who both have an interface each, how would I be able to add the properties of Class A and B together? For instance I wanted to associate firstitem with the seconditem.
public interface IAlpha
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/AddBravoToAlpha/{firstitem}/{seconditem}")]
void AddBravoToAlpha(int firstitem, int seconditem);
}
public interface IBravo
{
// what goes in here?
}
public Class Alpha
{
public Alpha()
{
AlphaAdd = new List<Bravo>();
}
int Firstitem { get; set }
public List<Bravo> AlphaAdd { get; set; }
}
public Class Bravo
{
public Bravo()
{
BravoAdd = new List<Alpha>(); //not sure if Bravo can access Alpha (derived class)
}
int Seconditem { get; set }
Guid Indexer { get; set }
public List<Alpha> BravoAdd { get; set; }
}
public Class BravoDoesAlpha : IBravo, IAlpha //????
{
List<Alpha> alpha = new List<Alpha>();
List<Bravo> bravo = new List<Bravo>();
public void AddBravoToAlpha(int firstitem, int seconditem)
{
var result = alpha.Where(n => String.Equals(n.Firstitem, firstitem)).FirstOrDefault();
var result1 = bravo.Where(n => String.Equals(n.Seconditem, seconditem)).FirstOrDefault();
if (result != null)
{
result.BravoAdd.Add(new Alpha() { Firstitem = firstitem });
}
if (result1 != null)
{
result1.AlphaAdd.Add(new Bravo() { Seconditem = seconditem });
}
}
}
Okay, so the question you are being asked is basically one about how to do a certain kind of refactoring known as "extracting" an interface.
This is one of the more easy refactorings to do and to understand if you understand interfaces vs. types.
All interfaces are types, but not all types are interfaces.
Now let's assume we are dealing in a world with two families of types: classes and interfaces (as in your example).
Instead of working your example directly, I will work a different but clearer example that does not use Alpha, Bravo, Charlie, Epsilon, etc. because this kind of stuff makes it harder to see the meaning.
First, here's the before:
public class Dog
{
public void Bark() { Console.WriteLine("Woof!"); }
public int NumberOfDogLegs { get { return 2; } }
public int NumberOfDogFriends { get; set; } // this can be set
private string SecretsOfDog { get; set; } // this is private
}
public class DoorBell
{
public void Chime() { Console.WriteLine("Ding!"); }
}
To extract the interface of a class, simply, well, extract all the public members of the class to an interface.
public interface IDog
{
void Bark();
int NumberOfDogLegs { get; }
int NumberOfDogFriends { get; set; }
}
public interface IDoorBell
{
void Chime();
}
Now to really make use of OOP, you can find a way to abstract IDog and IDoorBell. What do they have in common? Well, the obvious one is they both make a noise. So we make a new interface, public interface IMakeANoise and say that IDog and IDoorBell both implement it.
public interface IMakeANoise
{
void MakeNoise();
}
public interface IDog : IMakeANoise
{
void Bark();
int NumberOfDogLegs { get; }
int NumberOfDogFriends { get; set; }
}
public interface IDoorBell : IMakeANoise
{
void Chime();
}
And now we have a new method to implement on Dog and DoorBell.
public class Dog : IDog
{
public void Bark() { Console.WriteLine("Woof!"); }
public int NumberOfDogLegs { get { return 2; } }
public int NumberOfDogFriends { get; set; } // this can be set
private string SecretsOfDog { get; set; } // this is private
public void IMakeANoise() { Bark(); }
}
public class DoorBell : IDoorBell
{
public void Chime() { Console.WriteLine("Ding!"); }
public void IMakeANoise() { Chime(); }
}
Now let's say we are actually writing a video game and Dog and DoorBell are both things that we can show on the screen. Well, this makes them a lot bigger because we will need to provide more information like their coordinates, their states, etc.
In this case, Dog and DoorBell may be very different to us but are similar enough to potentially merit sharing a base class. (Really, this is a stretch, but it does get the point across.)
Without adding all those new interfaces and their implementations, let's just do the "sharing a base class" refactoring for what we already have.
public class RenderableThing : IMakeANoise, IDoAThousandOtherThings
{
protected virtual string MyNoiseToMake { get { return ""; } }
public virtual void MakeANoise()
{
Console.WriteLine(MyNoiseToMake);
}
}
public class Dog : RenderableThing, IDog
{
protected override string MyNoiseToMake { get { return "Woof!"; } }
public void Bark() { MakeANoise(); } // see what we did there?
// Notice that I am not declaring the method MakeANoise because it is inherited and I am using it by overriding MyNoiseToMake
public int NumberOfDogLegs { get { return 2; } }
public int NumberOfDogFriends { get; set; } // this can be set
private string SecretsOfDog { get; set; } // this is private
}
public class DoorBell : RenderableThing, IDoorBell
{
public void Chime() { Console.WriteLine("Ding!"); }
public override void MakeANoise()
{
Chime(); Chime(); Chime(); //I'll do it my own way!
}
}
You may wonder, what's the point? So we can do this...
IMakeANoise dogNoiseMaker = new Dog();
IMakeANoise doorBellNoiseMaker = new DoorBell();
IList<IMakeANoise> listOfNoiseMakers = new List<IMakeANoise>();
listOfNoiseMakers.Add(dogNoiseMaker);
listOfNoiseMakers.Add(doorBellNoiseMaker);
foreach (IMakeANoise noiseMaker in listOfNoiseMakers)
{
noiseMaker.MakeANoise();
}
// This will output
// Woof!
// Ding!
// Ding!
// Ding!
I'm going to take a shot in the dark and venture a guess that you don't quite understand what interfaces and inheritance is. I'll start off by explaining what interfaces are:
Interfaces contain only the definitions of methods, properties, events or indexers that an inheriting class must implement.
For example:
interface IExample
{
void HelloWorld();
}
class ExampleClass : IExample
{
public void HelloWorld()
{
Console.WriteLine("Hello world.");
}
}
Now for Inheritance; when you derive a class from a base class the derived class will inherit all members of the base class except for the constructors. Note: Depending on the accessibility of the members in the base class it's children may or may not be able to access the parents members.
public class Animal
{
public string Name { get; set; }
public Animal(string name)
{
Name = name;
}
public void Talk()
{
Console.WriteLine("{0} is talking", Name);
}
}
public class Cat : Animal
{
public Cat(string name) : base(name) { }
}
public class Dog : Animal
{
public string FurColor { get; set; }
public Dog(string name, string furColor) : base(name)
{
FurColor = furColor;
}
public void Greeting()
{
Console.WriteLine("{0} has {1} fur.", Name, FurColor);
}
}
class Program
{
static void Main(string[] args)
{
var cat = new Cat("Rex");
cat.Talk();
var dog = new Dog("Beanie", "Red");
dog.Talk();
}
}
I have the following interface:
public interface IObject{
double x {get;}
double y {get;}
List<IObject> List{get; set;}
}
and this class
public class Holder<T> where T : IObject {
private T myItem;
public void ChangeItemList(T item){
myItem.List = item.List;
}
However the compiler doesn't like the ChangeItemList method and on this line :
myItem.List = item.List;
gives me this error:
Cannot convert source type 'List<T>' to target type 'List<IObject>'
Why can't I do it and what is a good solution for this scenario?
thank you
I am not sure what you want to achieve but the following compiles and runs without exceptions:
class Program
{
static void Main(string[] args)
{
var holder = new Holder<IObject>();
holder.MyItem = new Object { List = new List<IObject>() };
holder.ChangeItemList(new Object { List = new List<IObject>() });
}
}
public class Object : IObject
{
public List<IObject> List { get; set; }
}
public interface IObject
{
List<IObject> List { get; set; }
}
public class Holder<T> where T : IObject
{
public T MyItem { get; set; }
public void ChangeItemList(T item)
{
MyItem.List = item.List;
}
}
Try to do this one- worked for me. The problem i had that myItem was null.
public class Holder<T> where T : IObject
{
private T myItem = Activator.CreateInstance<T>();
public void ChangeItemList(T item)
{
myItem.List = item.List;
}
}