Covariance problem facing in C#

Asked By 0 points N/A Posted on -
qa-featured

I have got class declared like this:

internal private abstract class BoxGroup<TS> : IBoxGroup where TS : SavedState

In that class I have this method:

protected virtual TS saveState() {
    return new SavedState(Width, Height);
}

I thought that this will be correct but I see red line under return statement and Resharper says that new SavedState(Width, Height) cannot be converted to TS. I don't know why. I thought that TS can by any class that extends SavedState but also SavedState itself. What can I do to correct it?

SHARE
Best Answer by Michelle Bang
Best Answer
Best Answer
Answered By 55 points N/A #104099

Covariance problem facing in C#

qa-featured

 

The error that you are facing has nothing to do with covariance that you mentioned because TS can be any class that is able to extend the Saved State. Generally the logic behind this is to create a new() constraint so that whatever type you make which is originally derived from Saved State should have a default constructor or an initializer. It is a common sense when doing this type of thing. That is why we have abstract functions too. But that's another case because in your case it simply means that your class is not able to have private setters.
 
try the following piece of code just in case you try to re write it.
 
  {
        public int Width{get; set;}
        public int Height{get; set;}
  }
  class SaveStateWithPi : SaveState
  {
        public double Pi
        {
            get{return Math.PI;}
        }
  }
  class Program
  {
     public static T CreateSavedState<T>(int width, int height)
            where T : SaveState, new()
            {
                       return new T
                       {
                           Width = width,
                           Height = height
                       };
            }
 
     static void Main(string[] args)
     {
        SaveState state = CreateSavedState<SaveStateWithPi>(5, 10);
        Console.WriteLine("Width: {0},Height: {1}",state.Width,state.Height);
     }
  }
}
 
Answered By 0 points N/A #104100

Covariance problem facing in C#

qa-featured

Thank you for the codes. It helps me correct the error. Thanks Techyv..

Related Questions