I have a sample program where I have a class called ObserverTest where I have two methods
one for subscription and one for notify for any type T but I get some build errors.
Following is my sample code>
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObserverTest obs = ObserverTest.Instance();
obs.SubscribeToChange<int>(GotChange);
obs.NotifyChange<int>(200);
Console.ReadLine();
}
private static void GotChange(int val)
{
Console.WriteLine(string.Format("Changed value is {0}", val));
}
}
public class ObserverTest
{
private static ObserverTest _obsTest;
private Action<T> _observer;
private ObserverTest()
{
}
public static ObserverTest Instance()
{
return _obsTest = _obsTest == null ? new ObserverTest() : _obsTest;
}
public void NotifyChange<T>(T val)
{
_observer(val);
}
public void SubscribeToChange<T>(Action<T> observer)
{
_observer = observer;
}
}
}
and followings are the errors:
Error 1 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Administrator\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 24 22 ConsoleApplication1
Error 2 The field 'ConsoleApplication1.ObserverTest._observer' cannot be used with type arguments C:\Users\Administrator\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 37 10 ConsoleApplication1
Can anyone please help me in removing the errors ?
Thanks in advance.
Try to add generic in the class definition:
complete code: