Answer the question
In order to leave comments, you need to log in
How to set list of types for generic in c#?
What is the right way to implement such a class? Thanks in advance
class Text<T> where (ulong | uint | byte)
{
private byte maxCharIndex = 255;
public string generateText(T textLength = 1)
{
char[] chars = new char[textLength];
Random r = new Random();
for (T i = 0; i < textLength; i++)
{
chars[i] = Convert.ToChar(r.Next(0, maxCharIndex));
}
return new string(chars);
}
}
Answer the question
In order to leave comments, you need to log in
No way. C# can't do
that. In this case, you can do it without a generic - just int.
class Text {
private static byte maxCharIndex = 255;
public static string generateText(int textLength = 1)
{
char[] chars = new char[textLength]; // всё равно размер для массивов задаётся интом
Random r = new Random();
for (T i = 0; i < textLength; i++)
{
chars[i] = Convert.ToChar(r.Next(0, maxCharIndex));
}
return new string(chars);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question