W
W
Wasya UK2021-09-29 21:10:28
C++ / C#
Wasya UK, 2021-09-29 21:10:28

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

1 answer(s)
V
Vasily Bannikov, 2021-09-29
@dmc1989

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 question

Ask a Question

731 491 924 answers to any question