Search code examples
c#functionclasssqlconnection

create extended 'copy' of existing c# class


There are many classes around like:

var db = new System.Data.SqlClient.SqlConnection();

you can use ist like:

db.Open();
db.Close();
//...

so what I'm searching for is a kind of perfect copy of the class:

public class SqlConnection{
    private System.Data.SqlClient.SqlConnection db;

    public SqlConnection() {
        //create SqlConnection
        db = new System.Data.SqlClient.SqlConnection();
    }
    public void Open() {
        db.Open();
    }
    //...
}

so that I can use it like a normal class, but with my own little customisations:

db.Open();
db.Close();
//...
db.MyOwnFunktion();

Is there a quick solution like a visual-studio-build-in function to do so?


Solution

  • One can do several things:

    1. Inheritance - create your own class that will inherit from a different one and will add more functionality
    2. Write extension methods - For your case of SqlConnection due to it being a sealed class that is what you should do (over option1)

    Short example of extension method:

    public static class Extensions
    {
        public static void DoSomething(this SqlConnection connection, int input)
        {
            //Do something
        }
    }
    
    //And then when you want to use it:
    SqlConnection connection = new SqlConnection();
    connection.DoSomething(3);