1

Well this is propably a duplicate, but I don't know what they are called so I dont know what to search for..

I have a function encrypting a string and returning a byte array (byte[]). Now I'd like the same function to return a string if required and other places I've used those sharp brackets to kinda tell the function what the output should be.
Like.

Security.Encrypt(data, "password") : returns byte[]
Security.Encrypt<string>(data, "password") : returns string

Now have I completely misunderstood the usage of those sharp brackets? What are they called? (then I might be able to google it myself) How do I access this eehm. modifier-thingey from my function?

Henrik Clausen
  • 679
  • 6
  • 16
  • 5
    It is called a generic method. Just google for it, there are mass of examples :) => https://www.dotnetperls.com/generic-method – Momo Nov 07 '17 at 07:48
  • 2
    They 'sharp brackets' are used with generics. That's the first term to Google, generics. I'm not familiar with the methods you are working with their but you the method needs to be created generic you can't just stick some 'pointy brackets' on it and expect it work. – Dave Nov 07 '17 at 07:48
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/ – Fildor Nov 07 '17 at 07:50
  • 2
    If you have some time to spare, get yourself a good book on C#. A good book should explain this and many other useful techniques. I myself enjoyed Jon Skeet's "C# in Depth". – S.L. Barth is on codidact.com Nov 07 '17 at 07:50
  • 5
    Actually, if you want to control the return type,only, generics are not the best way to go, imo. I'd suggest you better make two methods `byte[] EncryptToByteArray(..)` and `string EncryptToString(..)` – Fildor Nov 07 '17 at 07:52
  • Thanks guys. That ansvered my questions. I'll mark the ansver below as the right one allthough he just swooped in and said the same as the rest of you guys. – Henrik Clausen Nov 07 '17 at 20:17

1 Answers1

5

The angle brackets are called generics.

I don't think this is a correct usage of generics, since your method can only return a byte array or a string. Generics should be used when your method is applicable to all types or all implementing types of an interface. System.Collections.Generic.List<T> is such an example, you can create a list that stores any kind of object, so this is an appropriate use of generics.

Instead, try making them two separate methods - EncryptToString and EncryptToByteArray. The methods in the System.Convert class do this as well, since you can only convert to and from things like Int32, Int16, Boolean, it exposes separate methods to convert to each of these types.

For completeness, I'll show you how to get the generic parameter type.

Your method will be declared like this:

public T Encrypt<T>(string data, string password) {

}

Now T is the type the user put in, you can check it like this

if (typeof(T) == typeof(string))
Sweeper
  • 213,210
  • 22
  • 193
  • 313