I have two functions that do the basically same thing on two different classes.... each class has different properties.
For example:
public class ClassA
{
public int ColorID {get;set;}
public string ColorDescription {get;set;}
}
public class ClassB
{
public int TypeID {get;set;}
public string TypeDescription {get;set;}
}
public void ExFunctionSaveA(ClassA aClass)
{
aClass.ColorID=1;
aClass.ColorDescription="My Color";
Save();
}
public void ExFunctionSaveB(ClassB bClass)
{
bClass.TypeID=2;
bClass.TypeDescription="My Type";
Save();
}
As you can see the classes and the functions have the same type structure, just the property names are different... but I feel like I am repeating code doing this
Is there a way to make ExFunctionA and ExFunctionB into one function, so that I could use this for all classes that have similar structure
I know I could do some sort of generic thing like
public void ExFunctionSave<T>() // T is either ClassA or ClassB
{
.
.
.
.
Save();
}
but how would I handle the properties of each
Rather than using a generic, why not use inheritance to solve this?
public class theBase
{
string ID;
string Description;
}
public class theColor : theBase
{
}
public class theType : theBase
{
}
public void ExFunctionSaveA(theBase base)
{
base.ID=1;
base.Description="My Color";
Save();
}
If you can alter the definitions of your classes, then the best approach would be to make them implement a common interface that contains the properties you want to access:
public interface IDescribable
{
int ID { get; set; }
string Description { get; set; }
}
public class ClassA
{
public int ID { get; set; }
public string Description { get; set; }
public int ColorID
{
get { return ID; }
set { ID = value; }
}
public string ColorDescription
{
get { return Description; }
set { Description = value; }
}
}
public class ClassB
{
public int ID { get; set; }
public string Description { get; set; }
public int TypeID
{
get { return ID; }
set { ID = value; }
}
public string TypeDescription
{
get { return Description; }
set { Description = value; }
}
}
public void ExFunctionSave(IDescribable d, int id, string desc)
{
d.ID = id;
d.Description = desc;
Save();
}
Nothing more you can do unless the the 2 classes implement the same interface which has the function. In your case, even the function signatures are different.
You could define an Interface with attributes id and description.
The clases that has this structure could implement that interface.
And your method receive as parameter the interface and execute the moethods ...
Take a look at Reflection.
Reflection will let your code receive a ClassA, and discover that it has a ColourID and a ColorDescription. Likewise, when you receive a ClassB, you can discover its TypeID and TypeDescription. It's cool.
I would probably recommend a common interface, at least for your example, but if you're trying to something more complex and more generic, Reflection is the way to go.
Related
I created the GenericAttribute.cs file in my Models
public class GenericAttributes<T>
{
public T Id { get; set; }
public bool IsActive { get; set; }
public DateTime CreatedDate { get; set; }
}
Now I want to add 'int id' field in my User Model
public class User
{
//here I want to add 'Id' field
public string UserId { get; set; }
public string password { get; set; }
public string UserType { get; set; }
public int EmployeeId { get; set; }
public virtual Employee employee { get; set; }
}
How should I do this? Please help
You can make GenericAttributes an interface so you can implement it where ever.
Such as;
public interface IGenericAttributes<T>
{
//properties
}
And use in your class declaration;
public class User : IGenericAttributes<int>
{
//properties
}
This will force your concrete type User to implement the properties of the interface.
You are getting some conflicting answers due to your naming convention. Any class of the form xxxAttribute is expected to be a subclass of the Attribute class. Attributes are metadata that you can attach to classes, fields, etc. Using reflection you can read these attributes, which is a powerful way to inform various APIs about how to interact with your custom classes - without inheritance or an interface.
If this sort of metadata is your intent, then Barr J's answer is correct. However, if your intent is for the GenericAttributes class to serve as a base class that you can inherit these properties from, then Tom Johnson is correct (although he did change GenericAttributes into an interface instead of a base class, but same result if all you have are properties like this). The latter is most likely what you are looking for.
I would suggest renaming GenericAttributes to something more descriptive, like BaseRecord or IRecord (as an interface), since User looks like data coming from or going to a database.
It would also be handy to have a non-generic version of the class/interface so that you can non-generically reference such records.
public class BaseRecord {
public Type IdType { get; }
private Object _id = null;
public Object Id {
get {
return _id;
}
set {
if(value != null) {
if(!IdType.IsAssignableFrom(value.GetType()))
throw new Exception("IdType mismatch");
}
_id = value;
}
}
public bool IsActive { get; set; }
public DateTime CreatedTime { get; set; }
public BaseRecord(Type idType)
{
if(idType == null) throw new ArgumentNullException("idType");
this.IdType = idType;
}
}
namespace Generic {
public class BaseRecord<T> : BaseRecord
{
new public T Id {
get { return (T)base.Id; }
set { base.Id = value; }
}
public BaseRecord() : base(typeof(T))
{
}
}
}
public class User : Generic.BaseRecord<int>
{}
public class OtherRecord : Generic.BaseRecord<string>
{}
// This inheritence scheme gives you the flexibility to non-generically reference record objects
// which can't be done if you only have generic base classes
BaseRecord r = new User();
r = new OtherRecord();
BaseRecord records[] = { new User(), new OtherRecord() };
To access the id for GenericAttributes class, you'll have to cast User object as base class type.
namespace SampleApp
{
class SampleProgram
{
static void Main(string[] args)
{
User User = new User() { Id = 1 };
var genericAttribute = (User as GenericAttributes<int>);
genericAttribute.Id = 2;
var genericAttributeId = genericAttribute.Id;
var classId = User.Id;
}
}
public class GenericAttributes<T>
{
public T Id { get; set; }
}
public class User : GenericAttributes<int>
{
public new int Id { get; set; }
}
}
I have an class object from an external library that I want to add some additional properties to.
Let's say the external class is:
public class ExternalClass
{
public string EXproperty1 {get;set;}
public string EXproperty2 {get;set;}
public string EXproperty3 {get;set;}
public ExternalClass(){}
}
and I have a list of these object which gets populated as
List<ExternalClass> listOfExternalClass=new List<ExternalClass>();
listOfExternalClass=GetListOfExternalClass();
I can extend this class by creating a new class, adding the additional properties and making the external class a property.
public class NewClass
{
public ExternalClass ExternalClass {get;set;}
public string NewProperty1 {get;set;}
public string NewProperty2 {get;set;}
public NewClass(){}
public NewClass(ExternalClass externalClass){
this.ExternalClass=externalClass;
}
}
But to convert by original list of the external classes to a list of the new classes I would have to create a new list of new classes and iterate through the original list creating a new object and adding it to the list, like
List<NewClass> listOfNewClass=new List<NewClass>();
foreach(var externalClass in listOfExternalClass)
{
listOfNewClass.Add(new NewClass(externalClass));
}
I would then be able to access the external properties like
listOfNewClass.FirstOrDefault().ExternalClass.EXproperty1;
Can I do this with inheritance or is there a more efficient method?
Ideally I would like to end up with by calling the properties like:
listOfNewClass.FirstOrDefault().EXproperty1;
This can certainly be done with inheritance. Consider the following.
//Inherit from our external class
public class NewClass: ExternalClass
{
//Note we do not have a copy of an ExternalClass object here.
//This class itself will now have all of its instance members.
public string NewProperty1 {get;set;}
public string NewProperty2 {get;set;}
//If it has parameters include those parameters in NewClass() and add them to base().
//This is important so we don't have to write all the properties ourself.
//In some cases it's even impossible to write to those properties making this approach mandatory.
public NewClass()
{
}
}
Few things to know:
Your code is called a wrapper. This is because it "wraps" another class or group of classes.
You cannot inherit from class marked as sealed.
In C# classes are not sealed by default. If they're sealed the developer has intentionally prevented you from inheriting from the class. This is usually for a good reason.
If you can actually extend the External class that would be easy to accomplish:
public class NewClass: ExternalClass
{
public string NewProperty1 {get;set;}
public string NewProperty2 {get;set;}
public NewClass(){}
public NewClass(ExternalClass externalClass){
// you would have to copy all the properties
this.EXproperty1 = externalClass.EXproperty1;
}
}
Yes inheritance is what you are looking for:
public class ExternalClass
{
public string EXproperty1 { get; set; }
public string EXproperty2 { get; set; }
public string EXproperty3 { get; set; }
public ExternalClass() { }
}
public class NewClass:ExternalClass
{
public string NewProperty1 { get; set; }
public string NewProperty2 { get; set; }
public NewClass() { }
}
If you wish for (or need) delegation instead of a copy you can do:
public class NewClass
{
public ExternalClass ExternalClass {get;set;}
public string NewProperty1 {get;set;}
public string NewProperty2 {get;set;}
public string EXproperty1 {get { return this.ExternalClass.EXproperty1; };set{ this.ExternalClass.EXproperty1 = value; }; }
public string EXproperty2 {get { return this.ExternalClass.EXproperty2; };set{ this.ExternalClass.EXproperty2 = value; }; }
public string EXproperty3 {get { return this.ExternalClass.EXproperty3; };set{ this.ExternalClass.EXproperty3 = value; }; }
public NewClass(){}
public NewClass(ExternalClass externalClass){
this.ExternalClass=externalClass;
}
}
Instead of working against specific types, work against interfaces.
Below I am showing a mix of facade pattern and adapter pattern to 'transform' external data to a well-defined interface (IDocument), effectively abstracting things your are working on.
Example 1 : query about an interface
Here are the types you'll work against:
public interface IDocument {
string Name { get; set; }
}
public interface IMetadata {
string[] Tags { get; set; }
}
This is your own representation, should you need any:
public class RichDocument : IDocument, IMetadata {
public string Name { get; set; }
public string[] Tags { get; set; }
}
This is the wrapper against external data:
(a bastard mix of facade and/or adapter concepts)
public class ExternalClass {
public string Whatever { get; set; }
}
public class ExternalDocument : IDocument /* only a basic object */ {
private readonly ExternalClass _class;
public ExternalDocument(ExternalClass #class) {
_class = #class;
}
public string Name {
get { return _class.Whatever; }
set { _class.Whatever = value; }
}
}
And a demo on how to use all that:
internal class Demo1 {
public Demo1() {
var documents = new List<IDocument> {
new ExternalDocument(new ExternalClass()),
new RichDocument()
};
foreach (var document in documents){
var name = document.Name;
Console.WriteLine(name);
// see if it implements some interface and do something with it
var metadata = document as IMetadata;
if (metadata != null) {
Console.WriteLine(metadata.Tags);
}
}
}
}
Example 2 : query about a component
This is a bit more involved by pushing the concept to treat everything in an uniform manner, you can find it in .NET framework, game development or whatever ...
Definitions you'll work against:
public interface IContainer {
IList<IComponent> Components { get; }
}
public interface IComponent {
// it can be/do anything
}
Some components you'll query about:
public interface IDocument : IComponent {
string Name { get; set; }
}
public interface IMetadata : IComponent {
string[] Tags { get; set; }
}
Your 'internal' type:
public class Container : IContainer {
public Container() {
Components = new List<IComponent>();
}
public IList<IComponent> Components { get; }
}
Your 'wrapper' against external data:
public class ExternalClass {
public string Whatever { get; set; }
}
public class ExternalContainer : IContainer {
private readonly List<IComponent> _components;
public ExternalContainer(ExternalClass #class) {
_components = new List<IComponent> {new ExternalDocument(#class)};
}
public IList<IComponent> Components {
get { return _components; }
}
}
public class ExternalDocument : IDocument {
private readonly ExternalClass _class;
public ExternalDocument(ExternalClass #class) {
_class = #class;
}
public string Name {
get { return _class.Whatever; }
set { _class.Whatever = value; }
}
}
And a usage example:
public class Demo2 {
public Demo2() {
var containers = new List<IContainer> {
new ExternalContainer(new ExternalClass()),
new Container()
};
foreach (var container in containers) {
// query container for some components
var components = container.Components;
var document = components.OfType<IDocument>().FirstOrDefault();
if (document != null) {
Console.WriteLine(document.Name);
}
var metadata = components.OfType<IMetadata>().FirstOrDefault();
if (metadata != null) {
Console.WriteLine(metadata.Tags);
}
}
}
}
Notes
The problem with inheritance is that it is a very rigid approach and generally once you start doing it and at some point you hit a wall and want to revert, it's hard to get out of it.
By working against abstractions things are more flexible and things are decoupled.
Here are two examples that might incite you to change your approach:
Composition over inheritance
Using Components
I have the below code in my Application.
public class GeneralInfo
{
private string _id;
private string _name;
public string id
{
set
{
_id = value;
}
get
{
return _id;
}
}
public string name
{
set
{
_name = value;
}
get
{
return _name;
}
}
}
public class SecureInfo
{
private string _password;
public string password
{
set
{
_password = value;
}
get
{
return _password;
}
}
}
public class User
{
}
I need to apply multiple inheritance in the above code ie. the classes GeneralInfo,SecureInfo properties should be accessible in the user class.
I know using interface Multiple inheritance can be achieved. But i need to define the properties in the base class which is restricted in Interface.
How I can achieve this?
C# does not support multiple inheritance. However you can achieve this via multiple interfaces.
public interface ISecureInfo
{
}
public interface IGeneralInfo
{
}
public class UserClass : ISecureInfo, IGeneralInfo {
}
You probably better off encapsulating the data in the class rather than trying to use something to do multiple inheritance here. See this question for some arguments for this.
You can achieve this through interface based inheritance:
public interface IGeneralInfo
{
String Id { get; set; }
String Name { get; set; }
}
public interface ISecureInfo
String Password { get; set; }
}
public class User : IGeneralInfo, ISecureInfo
{
// Implementation of IGeneralInfo
public String Id { get; set; }
public String Name { get; set; }
// Implementation of ISecureInfo
public String Password { get; set; }
}
Or, going one step further, through composition:
public interface IGeneralInfo
{
String Id { get; set; }
String Name { get; set; }
}
public class GeneralInfo : IGeneralInfo
{
public String Id { get; set; }
public String Name { get; set; }
}
public interface ISecureInfo
String Password { get; set; }
}
public class SecureInfo : IGeneralInfo
{
public String Password { get; set; }
}
public class User : IGeneralInfo, ISecureInfo
{
private GeneralInfo generalInfo = new GeneralInfo();
private SecureInfo secureInfo = new SecureInfo();
public String Id {
get { return generalInfo.Id; }
set { generalInfo.Id = value; }
}
public String Name {
get { return generalInfo.Name; }
set { generalInfo.Name = value; }
}
public String Password {
get { return secureInfo.Password; }
set { secureInfo.Password = value; }
}
}
From your sample description, encapsulation might be what you might want to use:
public class Info{
GeneralInfo general;
SecureInfo secure;
...
}
You cannot do multiple inheritance in C# because it is not supported like C++. In C# you can use interfaces for it and implement method and properties. For sample, you could have a base class
public abstract class Entity
{
public string Name { get; set; }
}
You also could have some interfaces:
public interface IPrint
{
void Print();
}
public interface IGenerate
{
void Generate();
}
And use it like multiples inheritance (but it is not, it is just a single inheritance and interfaces)
public class User : Entity, IPrint, IGenerate
{
public void Print()
{
// some code
// here you could access Name property, because it is on base class Entity
}
public void Generate()
{
// some code
}
}
And you could instance it using the abstractions:
Entity e = new User();
IPrint p = new User();
IGenerate g = new User();
User u = new User();
If you need implementations, you could do a hiearachy inherits, for sample:
User inherit from Person that inherit from Entity.
public class Entity
{
public int Id { get; set; }
public void Method()
{
// some code
}
}
public class Person : Entity
{
public string Name { get; set; }
public void AnotherMethod()
{
// some code
}
}
public class User : Person
{
public string Password { get; set; }
public bool CheckUser(string name, string passworkd)
{
// some code
}
}
I think the best would be to seperate the implementation of the interfaces and the real class you have at the end.
What I mean is something like the Bridge Pattern.
Your class (that will implement several interfaces) will just deleagte the method calls to the real implementation, that you can have in a seperate place and only once.
You could also use an approach like this. You would get to the same point than if you would be using multiple inheritance. That way, you could inherit only Entity if you don't need the SecureInfo stuff (i.e. for books and other stuff). Still, I think composition would do better in this case as others say...
class User : SecuredEntity { }
abstract class SecuredEntity : Entity, ISecureInfo
{
public string Password { get; set; }
}
abstract class Entity : IGeneralInfo
{
public string ID { get; set; }
public string Name { get; set; }
}
interface IGeneralInfo
{
string ID { get; set; }
string Name { get; set; }
}
interface ISecureInfo
{
string Password { get; set; }
}
Slight newbie question.
I have a base class for payments. All share the same properties apart from additional extras. One of the properties is a postUrl. In the base this is empty but in the child classes each one has its own url. This should not be allowed to be accessed from outside the classes and it fixed and should not change. How do I go about overriding the property in a child class?
e.g.
class paymentBase
{
public int transactionId {get;set;}
public string item {get;set;}
protected virtual postUrl = String.empty; // can't be accessed from outside inheritance / public / protected?
public void payme();
}
class paymentGateWayNamePayment : paymentBase
{
protected override postUrl {
get { return "http://myurl.com/payme"; }
}
}
How would I go about doing this?
Thanks in advance
You should be able to accomplish it if you make your postUrl an actual virtual property, like this:
class paymentBase
{
public int transactionId {get;set;}
public string item {get;set;}
protected virtual postUrl { get { return String.Empty; }}
public void payme();
}
class paymentGateWayNamePayment : paymentBase
{
protected override postUrl {get { return "http://myurl.com/payme"; } }
}
I know this is a late entry but if you want the postUrl value to be set once by the sub class and then never again you need to make it a private value to the base class.
abstract class paymentBase
{
public paymentBase(string postUrl) { this.postUrl = postUrl; }
public int transactionId { get; set; }
public string item { get; set; }
protected string postUrl { get; private set; }
public void payme();
}
class paymentGateWayNamePayment : paymentBase
{
public paymentGateWayNamePayment() : base("http://myurl.com/payme") { }
}
Based on your requirements, I would recommend using an interface because posturl is a generic property that can be used on anything e.g. a page post back, a control post back, your class might use it etc.
This interface can be used as needed by any class.
interface IPostUrl
{
string postUrl { get; }
}
class paymentBase
{
public int transactionId {get;set;}
public string item {get;set;}
public void payme(){}
}
class paymentGateWayNamePayment : paymentBase, IPostUrl
{
public string postUrl
{
get { return "http://myurl.com/payme"; }
}
}
I have 2 web refs which I can't change:
They are almost identical but when referenced one only accepts ProperCase and the other Uppercamelcase.
Example
Not only props is the thing but entire classes with its props and methods
#EDIT: Sorry, I've realized it's more complicated than initially stated:
Not only props is the thing but entire classes with its props and methods and inner classes. Although only used as structures, inner classes have the same issue.
public class Foobar
{
public string Logmsgno;
public string Revno;
public string Reqsox;
public void Dosomething();
public Barbaz Mybarbaz;
public List<quux> Myquuxlist;
}
And the other has names like
public class FooBar
{
public string LogMsgNo;
public string RevNo;
public string ReqSox;
public void DoSomething();
public BarBaz MyBarBaz;
public List<Quux> MyQuuxList;
}
Is there an easy way to make an interface for both?
TIA!
Without a proper re-factoring to update everything and changing names, yes, you COULD with a little bit of smoke and mirrors. Create an interface based on the NEW values you WANT them to be, then change them to respectively use getter/setter to retain original and not break it.
To expand from your expanded question. You would have to adjust each of those levels too.. Define an interface for the "Barbaz" and "BarBaz" class so your outer class can have an object of
public interface IYourBarBazInterface
{
string BarBazProp1 { get; set; }
string AnotherProp { get; set; }
}
public interface IQuux
{
int QuuxProp { get; set; }
string AnotherQuuxProp { get; set; }
}
public interface IYourCommonInterface
{
string LogMsgNo { get; set; };
string RevNo { get; set; };
string ReqSox { get; set; };
// Similar principle of declarations, but interface typed objects
IYourBarBazInterface MyBarBaz { get; set; }
List<IQuux> MyQuuxList;
void DoSomething();
}
public class Foobar : IYourCommonInterface
{
public string Logmsgno;
public string Revno;
public string Reqsox;
public void Dosomething();
// your existing old versions keep same name context
// but showing each of their respective common "interfaces"
public IYourBarBazInterface mybarbaz;
public List<IQuux> myQuuxlist = new List<IQuux>();
// these are the implementations of the interface...
public string LogMsgNo
{ get { return Logmsgno; }
set { Logmsgno = value; }
}
public string RevNo
{ get { return Revno; }
set { Revno = value; }
}
public string ReqSox
{ get { return Reqsox; }
set { Reqsox = value; }
}
public void DoSomething()
{ Dosomething(); }
// Now, the publicly common Interface of the "IYourCommonInterface"
// that identify the common elements by common naming constructs.
// similar in your second class.
public IYourBarBazInterface MyBarBaz
{ get { return mybarbaz; }
set { mybarbaz = value; }
}
public List<IQuux> MyQuuxList
{ get { return myQuuxlist; }
set { myQuuxlist = value; }
}
}
public class FooBar : IYourCommonInterface
{
// since THIS version has the proper naming constructs you want,
// change the original properties to lower case start character
// so the interface required getter/setter will be properly qualified
public string logMsgNo;
public string revNo;
public string reqSox;
public IYourBarBazInterface MyBarbaz;
public List<IQuux> Myquuxlist;
// these are the implementations of the interface...
public string LogMsgNo
{ get { return logMsgMo; }
set { logMsgNo = value; }
}
public string RevNo
{ get { return revNo; }
set { revNo = value; }
}
public string ReqSox
{ get { return reqSox; }
set { reqSox = value; }
}
// Since your "DoSomething()" method was already proper case-sensitive
// format, you can just leave THIS version alone
public void DoSomething()
{ .. do whatever .. }
public IYourBarBazInterface MyBarBaz
{ get { return MyBarbaz; }
set { MyBarbaz = value; }
}
public List<IQuux> MyQuuxList
{ get { return myquuxlist; }
set { myquuxlist = value; }
}
}
Unfortunately, no. There's not. C# is case sensitive (including interfaces). To have them both conform to a single interface, the name case would have to match. If you did that, the classes would be the same anyway.
Your only option would be to create an interface that used one of the casing methods, implement it on both classes, and then add code to one class (with the naming convention you didn't chose) to pass through the calls:
public interface IFooBar
{
string LogMsgNo { get; set; }
string RevNo { get; set; }
string ReqSox { get; set; }
void DoSomething();
}
public class Foobar : IFooBar
{
public string Logmsgno;
public string Revno;
public string Reqsox;
public void Dosomething();
public string LogMsgNo
{
get { return Logmsgno; }
set { Logmsgno = value; }
}
// And so on
}
UPDATE
After seeing your edit, things become much more complex. You'll have to do the same thing to all of the inner classes and then have your interfaces reference the lower level interfaces. Same concept, just more work.
If I had to handle this, I would likely write an extension method to convert from one type to another. Some reflection would do most of the work. new Foobar().ToFooBar().ToFoobar() Or write a class I would always interact with and at the last point you need to access the right implementation, call the ToFoobar().