How to store a single character?

2

My class has an attribute that is a single character. I can store as string , but I think the correct one would be char . But this attribute can receive a int (between 0 and 9) of another method. How do I save this number in this char with no error?

    
asked by anonymous 09.12.2017 / 22:27

3 answers

3

If you can guarantee that always will come between 0 and 9 is basically math:

using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() {
        var x = 2;
        WriteLine(ToChar(x + 48));
    }
}

See running on .NET Fiddle . And at Coding Ground . Also I placed GitHub for future reference .

48 is the decimal code of the ASCII table for the character representing 0. If it comes out of the range of 0 to 9 may not give the expected result, although in most cases will not have problems.

    
11.12.2017 / 13:48
0

I believe the best way would be to use string and to make it easier to encapsulate the conversion process or builder or create methods to encapsulate the value distribution:

using System;

namespace consoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var oneChar1 = new OneChar('a');
            Console.WriteLine(oneChar1.Property);

            var oneChar2 = new OneChar(1);
            Console.WriteLine(oneChar2.Property);
        }
    }

    public class OneChar
    {

        public OneChar(char c)
        {
            Property = Convert.ToString(c);
        }

        public OneChar(int i)
        {
            Property = Convert.ToString(i);
        }

        public string Property { get; private set; }

        public void SetProperty(char c)
        {
            Property = Convert.ToString(c);
        }

        public void SetProperty(int i)
        {
            Property = Convert.ToString(i);
        }
    }
}
    
10.12.2017 / 14:47
0

A string is a char[] , a string. I've done an extension method:

public static char ToChar(this string value) {
    if (string.IsNullOrEmpty(value)) throw new ArgumentException();

    // retorna o primeiro caractere da string
    // se não quiser usar o System.Linq, pode fazer "return value[0];"
    return value.First();
}

This method will do:

"a".ToChar();          // char 'a'
"1".ToChar();          // char '1'
"".ToChar();           // ArgumentException foi disparado
"321".ToChar();        // char '3'
"xyz".ToChar();        // char 'x'

It always returns the first character. For use with integers, see:

1.ToString().ToChar();  // char '1'

See running Ideone .

    
09.12.2017 / 22:39