FPGA
FPGA

Reputation: 3855

C# classes that implement the same properties

I have a couple classes that have the same properties.

For example

public class Decimalclass
{
   public string SqlColumnName {get;set;}
   public SqlDbType SqlColumnType {get;set;}
   public Decimalclass()
   {
      SqlColumnType = SqlDbType.Decimal;
   }
   //...
}

public class Textclass
{
  public string SqlColumnName {get;set;}
  public SqlDbType  SqlColumnType {get;set;}
  public Textclass()
   {
      SqlColumnType = SqlDbType.NVarChar;
   }
   //...
}

public class Intclass
{
  public string SqlColumnName {get;set;}
  public SqlDbType  SqlColumnType {get;set;}
  public Intclass()
   {
      SqlColumnType = SqlDbType.Int;
   }
   //...
}

As you can see those classes share the same properties, I am trying to learn about interfaces and abstract classes.

Upvotes: 2

Views: 3381

Answers (2)

Wjdavis5
Wjdavis5

Reputation: 4151

I would do :

public abstract class BaseClass
{
  public string SqlColumnName {get;set;}
  public SqlDbType  SqlColumnType {get;set;}
}

public class Intclass : BaseClass
{
   public Intclass()
   {
      base.SqlColumnType = SqlDbType.Int;
   }
}

Updated to better answer the OPs Q

The Interface specifies a contract that must be followed on the object implementing the interface. Whilst the abstract base class provides a method to implement the interface automatically in all objects that inherit from it.

    interface IBase
    {
         string SqlColumnName { get; set; }
         SqlDbType SqlColumnType { get; set; }
    }

    public abstract class BaseClass : IBase
    {
        public string SqlColumnName { get; set; }
        public SqlDbType SqlColumnType { get; set; }
    }

    public class Intclass : BaseClass
    {
        public Intclass()
        {
            base.SqlColumnType = SqlDbType.Int;
        }
    }

So in that example the interface IBase says that all implementer must contain these two properties to meet the contract. This is useful especially when following an Inversion of Control IoC or Dependency Injection pattern. This allows you to implement the interface on new objects and maintain compatibility anything that takes an IBase as an argument. The abstract class implements the interface which is then inherited by any object that inherits from the base class. Basically by using the abstract base class you don't have to specifically implement each property in your child objects.

Upvotes: 5

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

I would make the SqlColumnType abstract and read-only to force implementing it in derived classes.

public abstract class BaseClass
{
    public string SqlColumnName { get; set; }
    public abstract SqlDbType SqlColumnType { get; }
}

public class Intclass : BaseClass
{
    public override SqlDbType SqlColumnType
    {
        get { return SqlDbType.Int;  }
    }
}

Upvotes: 4

Related Questions