Clase: DNI

Esta clase permite obtener la letra correspondiente al numero del DNI.

using System;
using System.Text.RegularExpressions;
 
namespace DNI
{
 
    class DNI
    {
        public const string CORRESPONDENCIA = "TRWAGMYFPDXBNJZSQVHLCKE";
        static public char LetraNIF(string dni)
        {
            Match match = new Regex(@"\b(\d{8})\b").Match(dni);
            if (match.Success)
            {
                return CORRESPONDENCIA[int.Parse(dni) % 23];
            }
            else
            {
                throw new ArgumentException("El DNI debe contener 8 dígitos.");
            }
 
        }
        static public char LetraNIE(string nie)
        {
            Match match = new Regex(@"\b([X|Y|Z|x|y|z])(\d{7})\b").Match(nie);
            if (match.Success)
            {
                int n = int.Parse(match.Groups[2].Value); // también se podría haber usado como parámetro nie.Substring(1, 7)
                switch (char.ToUpper(nie[0])) // también se podría haber usado como parámetro Char.ToUpper(((String)match.Groups[1].Value)[0])
                {
                    case 'X':
                        return CORRESPONDENCIA[n % 23];
                    case 'Y':
                        return CORRESPONDENCIA[(10000000 + n) % 23];
                    case 'Z':
                        return CORRESPONDENCIA[(20000000 + n) % 23];
                    default:
                        return '\0';
                }
            }
            else
            {
                throw new ArgumentException("El NIE debe comenzar con la letra X, Y o Z seguida de 7 dígitos.");
            }
 
        }
    }
}

Navegación

Software de programación

Ayuda al servidor