-2

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
chinakid
  • 3
  • 3

1 Answers1

0

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

Basil Kosovan
  • 888
  • 1
  • 7
  • 30
  • i wrote the following line in the main after i did the change( the name and the casting) : EncrypterDecrypter e1 = EncrypterDecrypterBuilder.Builder(eEncryptersDecrypters.Person); but during run time i get an invalid casting exception – chinakid Nov 30 '19 at 19:15
  • T is Entity. You can't cast EncrypterDecrypter to EncrypterDecrypter. Use public interface EncrypterDecrypter where T : Entity – Basil Kosovan Nov 30 '19 at 19:21
  • You want to cover a lot of stuff in this topic(and not related to your first issue). Start with this article https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/ – Basil Kosovan Nov 30 '19 at 19:24
  • I did what you suggested but i got the following error : https://imgur.com/8EexTtj – chinakid Nov 30 '19 at 19:26
  • Please start with understanding what is Covariance and Contravariance. Use link above. – Basil Kosovan Nov 30 '19 at 19:27
  • 1
    Thanks alot it works, I will read the article you gave in order to understand. – chinakid Nov 30 '19 at 21:16