Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Execute code before constructor

Tags:

c#

.net

I'd like to automagically execute some code before certain class constructor gets executed (to load some externall assmebly that class requires), all in C#, .NET 2.0

EDIT:

public class MyClass 
{
    ThisTypeFromExternalAssembly variable;
}

And what I really need is to have assembly loader that is 'attached' somehow to MyClass, to load externall assembly when it is needed. This must happen before constructor, but I would not like to need to call some Init() before constructing MyClass() object

like image 358
Adam Kłobukowski Avatar asked Dec 12 '22 15:12

Adam Kłobukowski


2 Answers

You can use the static initialiser for the class:

static ClassName( )
{

}

This will be called before any instances of ClassName are constructed.

Given the update you would do:

public class MyClass
{
    ThisTypeFromExternalAssembly variable;

    static MyClass( )
    {
        InitialiseExternalLibrary( );
    }

    public MyClass( )
    {
         variable = new ThisTypeFromExternalAssembly( );
    }
}
like image 146
Nick Avatar answered Dec 23 '22 23:12

Nick


Could you use a static constructor for this?

class SimpleClass
{
    // Static constructor
    static SimpleClass()
    {
        //...
    }
}

From the MSDN article:

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

like image 30
Dave Avatar answered Dec 23 '22 23:12

Dave