As I recently found out int?
and Nullable<int>
are not always interchangeable. (Of course this is true for all type that has a Nullable
counterpart, not just int
.)
What I wonder about: is there a way to construct valid C# code in which you can replace int?
with Nullable<int>
(some occurences, so not all, but not necessarily only one) and get a still valid C# code, with different meaning?
I don't count examples as solutions in which the int?
and Nullable<int>
are part of a string literal, so this trivial case is not what i am looking for:
if ("int?".Contains("int?"))
Console.WriteLine("true");
else
Console.WriteLine("false");
// prints "true"
if ("int?".Contains("Nullable<int>"))
Console.WriteLine("true");
else
Console.WriteLine("false");
// prints "false"
Also here is a more complex version, which still uses strings, but shows you that it is very well possible to write code with only this difference leading to different meanings (unfortunately only one version is valid C#):
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerResults results = codeProvider.CompileAssemblyFromSource(new CompilerParameters(), "using System; class Foo { static void Main() { int a=1; var test = a is Nullable<byte> & true; } }");
Console.WriteLine(results.Errors.Count > 0 ? "false" : "true");
// prints "true"
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerResults results = codeProvider.CompileAssemblyFromSource(new CompilerParameters(), "using System; class Foo { static void Main() { int a=1; var test = a is byte? & true; } }");
Console.WriteLine(results.Errors.Count > 0 ? "false" : "true");
// prints "false"
(On why one compiles while the other doesn't I recommend you to check out this question and answer.)
So my question is can you construct code like that? If not then why not?