C
C#9mo ago
cheeze2000

Creating a function that accepts either string or byte[]

i have some function that is supposed to perform AES 256 encryption, EncryptAes(byte[] plaintext, byte[] key) the problem is i want this function to accept either string or byte[] but then i have to declare 3 other function overloads. So my approach was something like EncryptAes(EncryptionInput plaintext, EncryptionInput key) and then a bunch of public static implicit operators. is this a good approach?
3 Replies
leowest
leowest9mo ago
why 3 other functions? would it not be just
... EncryptAes(string plaintext, byte[] key)
{
// convert string to bytes
// call original function
}
... EncryptAes(string plaintext, byte[] key)
{
// convert string to bytes
// call original function
}
Or u mean that because u want a combination of string and bytes for both inputs? I think the overload path is fine because its straightforward and simple 3 lines wouldn't bother me. But a class that takes a byte array or a string may sound more confusing.
Neophyte
Neophyte9mo ago
I second to that. Overloads create a more straight forward, logical path, reduce the potential branching during code execution (hence helping performance). You can still abstract common logic afterwards. Maybe your overloads could simply convert the incoming object to a byte[] and then call the EncryptAes(byte[] key) ?
cheeze2000
cheeze2000OP9mo ago
yes correct, basically 4 different combinations
Want results from more Discord servers?
Add your server