Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
How to cast T To Nullable<T>

I have a generic method and need to guarantee that my method returns nullable<T>(ex. source is List<int> or List<int?> must returns int?) and I want to return null instead of default (ex. default of int is 0. in this case I want to return null). It can be possible to add constraints on type parameter(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters) but whit this approach I must have 2 methods (one of them with struct constraint and another with class constraints)

my method is:

public static T? ElementOrNull<T>(List<T> source, int? index)
{
    if (source == null || index == null || source.Count <= index)
        return null;
    return source[index.Value];
}

I try Convert.ChangeType() and reflection(Activator.CreateInstance() and Activator.CreateInstance<T?>()) but I can't solve this problem.

Any and all feedback is appreciated. Thank you

Note: I checked all the questions about generics and casting of them in StackOverflow but they didn't help me

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Generics constraints are not part of the method signature, but compiler still needs to know if T is value or reference type to convert null to T and handle ? in T? correctly. But you can help the compiler using optional constrained parameters this way:

public class ReqStruct<T> where T : struct
{
}

public class ReqClass<T> where T : class
{
}

public static T? ElementOrNull<T>(List<T> source, int? index, ReqStruct<T> req = null) where T : struct
{
    if (source == null || index == null || source.Count <= index)
        return null;
    return source[index.Value];
}

public static T? ElementOrNull<T>(List<T> source, int? index, ReqClass<T> req = null) where T : class
{
    if (source == null || index == null || source.Count <= index)
        return null;
    return source[index.Value];
}

And since the parameters are optional the usage will look like:

var intOrNull = MethodHolder.ElementOrNull(new List<int> { 1 }, 5); // var is int?
var objOrNull = MethodHolder.ElementOrNull(new List<object>(), 5); // var is object?
over 4 years ago · Santiago Trujillo Relatório

0

My preferred approach to this is to use a custom Option/Maybe type. I.e. a struct with a generic value and a bool to describe if the value is valid or not. I.e. never use null, always use a Maybe for optional parameters/return values:

public static Maybe<T> ElementOrNone<T>(List<T> source, Maybe<int> index)
{
    if (source == null || !index.HasValue || source.Count <= index.Value)
        return Maybe<T>.None;
    return source[index.Value];
}

While Nullable<T> and non-nullable references help to avoid null reference exceptions, I find them lacking when writing generic code, in part due to the problem you are describing.

Using a custom type have the advantage of consistent behavior for both value and reference types, and can allow for various extensions to make working with values easier, potentially even using linq query syntax to combine multiple values. A downside is that it is a custom type, so more to learn.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda