3

Lets suppose if I have created a C# project which uses C# 4.0 features - optional parameter. What will happen if I select '.Net Framework 2.0' as a target framework? Will the compiler be intelligent enough to generate IL compatible with 2.0 on its own or will the Exe give runtime error when deployed on a machine that has only .Net framework 2.0?

Kevin
  • 53,822
  • 15
  • 101
  • 132
FIre Panda
  • 6,537
  • 2
  • 25
  • 38

1 Answers1

4

In the specific case of optional parameters, compatibility will work as default values to use are stored in the caller's assembly and not in the called assembly so compatibility with other assemblies is ensured. If it compiles, it will run.

Optional parameters are just a syntaxic sugar. The following code compiles and run for a target framework 2.0 :

internal class Program
{
    public static class DummyClass
    {
        public static string Bar(int b = 10, int a = 12)
        {
            return a.ToString();
        }
    }

    private static void Main(string[] args)
    {
        Console.WriteLine("{0}", DummyClass.Bar(a: 8));

        Console.ReadKey();
    }
}

Read a full explanation by Mr Botelho

AlexH
  • 2,650
  • 1
  • 27
  • 35
  • 1
    This answer is correct for the specific case, but wrong for the general one. – Wilbert Dec 23 '13 at 10:14
  • I agree, in most other cases it will just not compile – AlexH Dec 23 '13 at 10:15
  • Excellent explanation Alex. What about auto implemented properties public string str {get; set;} will these work fine if targeted framework is set to .Net 2.0? – FIre Panda Dec 23 '13 at 11:09
  • [Optional, DefaultParameterValue(...)] gets added to method having optional paramater. I am wondering how come .Net framework 2.0 gets aware of this attribute as it is a .Net 4.0 thing? http://naveensrinivasan.com/2010/04/16/exploring-internal-implementation-c-4-0-default-and-optional-arguments/ – FIre Panda Dec 23 '13 at 11:20
  • 1
    It will work too: Auto properties are just syntax sugar and are backward comptible to .net 2.0 : http://stackoverflow.com/questions/9393982/why-are-my-auto-implemented-properties-working-in-asp-net-2-0 – AlexH Dec 23 '13 at 12:31
  • Both Optional and DefaultParameterValue attributes exist in .net 2.0 http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.defaultparametervalueattribute(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.optionalattribute(v=vs.80).aspx – AlexH Dec 23 '13 at 12:35