forum

Home / DeveloperSection / Forums / Creating own Event for initialization of an object

Creating own Event for initialization of an object

Royce Roy 1833 19-Dec-2014

So I was trying to create my own event for the initialization of a class called Car, which inherits from an Automobile object. Below is the same in C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abc.Training.Artifacts;
 
namespace Abc.Training.Objects
{
    public abstract class Automobile
    {
        public string Model { get; set; }
        public string Manufacturer { get; set; }
        public string YoM { get; set; }
    }
 
    public class Car : Automobile
    {
        public static event Delegates.ObjectInitHandler OnInit;
 
        public string MarketSegment { get; set; }
        public int BootSpace { get; set; }
 
        public Car(string model, string manufacturer, string yom)
        {
            Model = model ;
            Manufacturer = manufacturer;
            YoM = yom;
            ObjectInitEventArgs eArgs = new ObjectInitEventArgs();
            eArgs.IsResidentObject = true;
            eArgs.ObjectType = this.GetType();
            if (OnInit != null) OnInit(this, eArgs);
        }
 
    }
}

The ObjectInitHandler and its args (the delegate type used here) is also created by me as: ` 

public delegate void ObjectInitHandler(object sender, ObjectInitEventArgs e);
 public class ObjectInitEventArgs:EventArgs
    {
        public Type ObjectType { get; set; }
        public bool IsResidentObject { get; set; }
    }`

 I am subscribing to the event as below: ` 

Car.OnInit += new Delegates.ObjectInitHandler(Car_OnInit);//able to do this as event is static

Car c = new Car("Maruti", "Maruti", "2004");

void Car_OnInit(object sender, ObjectInitEventArgs e)

{

   Console.WriteLine("Car object initialized");

}` 

I wanted to create an event OnInit for this class. However, if I put an instance event OnInit in the publisher (my Car class), I will have to initialize the class first before I can subscribe to this event. Since I would like to fire this event on initialization, this becomes a chicken and egg problem for me.

 I solved it by creating a static event Object and doing the subscription before the object initialization as shown below (this is a snippet from the code above itself): 

public static event Delegates.ObjectInitHandler OnInit; 

However, in an ASP.NET application, this would mean if multiple users access this application, I will have the same delegate object that will have duplicate subscriptions of events (because its static), which is obviously not cool.

 Is there a design pattern which I can follow to have the event also as an instance member but still I can subscribe to the event before instantiation?


Updated on 20-Dec-2014

Can you answer this question?


Answer

2 Answers

Liked By