Click here to Skip to main content
11,496,146 members (517 online)
The site is currently in read-only mode for maintenance. Posting of new items will be available again shortly.
See more: C#
I have different object classes like:

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,


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

SetValues(objectType T){ }

can this be achieved using generics or abstract methods or some other better way in C#.
Posted 16-Aug-14 13:56pm
Edited 16-Aug-14 14:44pm
These are not classes, that you're showing us. Classes are made using the class keyword. Like this

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

   // 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.
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

interface IValues
  void SetValues();

Then your classes would implement this

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

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 10,401
1 OriginalGriff 8,910
2 Sascha Lefèvre 3,899
3 Maciej Los 3,422
4 Richard Deeming 2,600

Advertise | Privacy | Mobile
Web04 | 2.8.150520.1 | Last Updated 16 Aug 2014
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100