Click here to Skip to main content
16,020,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have different object classes like:

C#
public object1{
  public string prop1 {get; set;}
  public int prop2 {get; set;}
}

public object2 {
  public int prp1 {get; set;}
  public bool prp2 {get; set;}
}


I want to make a common function which accepts these objects as parameter as,

C#
SetValues(object1);
SetValues(object2);


and in SetValues function object will be created according to their type and values will be filled in their properties something like;

C#
SetValues(objectType T){ }


can this be achieved using generics or abstract methods or some other better way in C#.
Posted
Updated 16-Aug-14 13:44pm
v2

These are not classes, that you're showing us. Classes are made using the class keyword. Like this

C#
public class Object1 {
   public string prop1 {get; set;}
   public int prop2 {get; set;}
}
 
public class Object2 {
   public int prop1 {get; set;}
   public bool prop2 {get; set;}
}


You can have same names among different classes. There is no need to name them differently, since they're in different classes. But you weren't having them in different classes, you were having them in different don't-know-whether-that-was-a-class-or-function-or-whatever thing.

Once you do so you will have the classes. To create such a function I think you will do this

C#
SetValues(T){
   // go your code here. It will accept the objects
}


You can pass either first object or the second. You were having an extra parameter data type, of objectType, which would have caused compiler error. C# allows generic types, so it is ok to let the compiler handle what would be better to cast the object to.
 
Share this answer
 
v2
Everything that Afzaal Ahmad Zeeshan is correct.

The only way I can think of is by using an interface where the interface is implemented in object1 and object2.

You could then call it by using an interface reference to an object that implements that interface

C#
interface IValues
{
  void SetValues();
}


Then your classes would implement this

C#
public class object1 : IValues
{
  public void SetValues(IValues refIvalues);
}

public class object2 : IValues
{
  public void SetValues(IValues refIvalues);
}


By referencing interface IValues in the paramaters it will only accept classes or objects that implement IValues. This way you are gaurenteed by the compiler that you will get passed the correct type
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900