Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect c# version at compile time

I have an old line of c# code that looks basically like this:

foo.set_Parent(parent);

It has compiled fine for years. Now in VS2015 I get the error:

CS0571 'Foo.Parent.set': cannot explicitly call operator or accessor

So I can rewrite the line as:

foo.Parent=parent;

This builds fine in VS2015, but in VS2013 it gives the error:

'Foo.Parent' is not supported by the language; try directly calling accessor methods 'Foo.get_Parent()' or Foo.set_Parent(Foo)'

So the simple fix is to simply ifdef these two lines based upon which version of the compiler is running. But how do you detect which version of the compiler is executing?

And for the record, no, I can't just dictate that everyone on the team simultaneously upgrades to VS2015.

Additional info - For everyone smelling a rat, I'll go ahead and drag out the ugly truth, although I don't think it will change much of anything. The class Foo is from an ancient Borland assembly that is all bound up in Delphi (and yes, we're migrating away but not there yet). So the actual code, that compiles up to VS2013, looks like this:

using Borland.Vcl;
using RepGen;
using SnapReportsForm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace MigrantCOM {
   [ComVisible(true)]
   [Guid("48245BA3-736B-4F98-BDC5-AD86F77E39F4")]
   [ProgId("MigrantCOM.Exports")]
   [ClassInterface(ClassInterfaceType.AutoDual)]
          public class MigrantCLRExports {   // : MarshalByRefObject 
      public string Test(string s) { return s+s; }
   }

   [ComVisible(true)]
   [Guid("1154D364-B588-4C31-88B9-141072303117")]
   [ProgId("MigrantCOM.SnapRepCOM")]
   [ClassInterface(ClassInterfaceType.AutoDual)]
   public class SnapRepCOM {
      TRepGen repGen;
      TStringList snapRefs=new TStringList();
      TForm parent=new TForm(null);
      TMemo designerMemo;
      List<TReference> references=new List<TReference>();
      TRunAsSnapContext runAsSnapContext=new TRunAsSnapContext();

      public SnapRepCOM() {
         designerMemo=new TMemo(parent); designerMemo.set_Parent(parent);
         ...
      }

So the class being instantiated is Borland.Vcl.TMemo which is part of the old Delphi assembly.

like image 587
Kevin Donn Avatar asked Dec 16 '15 16:12

Kevin Donn


1 Answers

I'm leaving this as an answer, linking an image will fit better here than in a comment.

So if you want to use VS 2015 but still use the same good ol' version of the C# language that worked for years, you can configure your project to target a specific version:

enter image description here

This adds <LangVersion>5</LangVersion> in the csproj.

like image 118
ken2k Avatar answered Oct 06 '22 17:10

ken2k