Search code examples
c#genericsabstraction

Problem building a generic inherited class in C#


I wrote the following classes and I don't know why the line:

return new PersonEncrypterDecrypter()

which is in the class EncrypterDecrypterBuilder<T> does not work.

It is said that that casting is not allowed but I do not see any reason that it should be a problem.

Here is a link to the code :

http://coliru.stacked-crooked.com/a/2f10c6bb11a3c79d

Edit: did some changes (the link to the code is updated).

I wrote a main method like this:

EncrypterDecrypter<Entity>e1 = 
EncrypterDecrypterBuilder<Entity>.Builder(eEncryptersDecrypters.Person);
 Dictionary<string, string> dic = e1.DataDecrypter(test);

and I get an System.InvalidCastException when trying to execute the first line:

return (EncrypterDecrypter<T>)(new PersonEncrypterDecrypter())

which is in the class EncrypterDecrypterBuilder


Solution

  • The first issue is with static class EncrypterDecrypterBuilder method. Static constructor couldn't have a parameter and can't return a value. Looks like you just want to have a static method. Rename this method. Also, you will need to cast the object in return clause

    public static class EncrypterDecrypterBuilder<T> where T : Entity
    {
        public static EncrypterDecrypter<T> EncrypterDecrypterBuilderSomeNewName()
        {
    
            return (EncrypterDecrypter<T>)(new PersonEncrypterDecrypter());
        }
    }
    

    See all code:http://coliru.stacked-crooked.com/a/6a3d3fef3b7af7f2