Unable to use primary constructor parameter - c#-6.0

I am playing with new features of C# 6.0I have the following line of code
public class Circle(int radius)
{
public double circumference => 2 * 3.14 * radius;
}
Above code doesn't work and gives an error "The name radius doesn't exist in current context"
but when I use
public class Circle(int radius)
{
int Radius = radius;
public double circumference => 2 * 3.14 * Radius;
}
code just works fine.
Is this Some sort of bug from VS as its CTP or something is wrong with my code. as i believe i should be able to use parameter of primary constructor inside the constructor whithout setting it to some other variable.

Well, this may doesn't answer your question directly but primary constructor has been withdrawn from C# 6.0.
See: Changes to the language feature set and this question: Primary constructors no longer compile in VS2015
You are probably trying your code in Visual Studio 2014 CTP. You need to download and install new version of Visual Studio 2015 Preview. (but first you have to un-install Visual Studio 2014 CTP)
You may see the latest: Languages features in C# 6 and VB 14

According to the MSDN magazine article on the new language features:
By default, primary constructor parameters aren’t accessible outside of an initializer.
So you can't use them directly within any methods, which your calculated getter is.

Related

In Visual Studio 2017/2015 C++/CLI Find All References FAILS

I am having difficulty with Find All References feature in Visual Studio 2017 (and 2015 at least, may be older too).
I have this defined in one project (C#):
public static class AlgorithmNames
{
public static readonly string
FaceAnalyzerAlgorithm = "Face Analyzer Algorithm (C++)",
StaticFaceAnalyzerAlgorithm = "Static Face Analyzer Algorithm (C++)";
}
and it's used in another project (C++/CLI) in the same solution like so:
public ref class FaceAnalyzerAlgorithm : AlgorithmBase
{
public:
property String^ Name
{
String^ get() override { return AlgorithmNames::FaceAnalyzerAlgorithm; }
};
...
When I right click Find All References on the definition of FaceAnalyzerAlgorithm (C#) it does not find the use just the definition even though the filter says "Entire Solution".
When I right click Find All References on the use (C++/CLI) it finds nothing and nothing happens in UI to indicate any activity. Go To Definition and Go To Declaration both end up in Object Browser.
Issues like this do not seem to happen when it's just C#, but as soon as there is C++ it fails miserably. Any fixes or workarounds welcome.

Error when using std::make_move_iterator to insert a std::list<std::unique_ptr>> into another one

I've been reading this answer about moving elements from a std::vector<std::unique_ptr<T>> to another one using std::make_move_iterator. It works flawlessly:
std::vector<std::unique_ptr<int>> c1;
std::vector<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
c2.insert(c2.end(), std::make_move_iterator(c1.begin()), std::make_move_iterator(c1.end()));
Now I tried to change it to use a different container (std::list):
std::list<std::unique_ptr<int>> c1;
std::list<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
c2.insert(c2.end(), std::make_move_iterator(c1.begin()), std::make_move_iterator(c1.end()));
But compilation fails with:
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
However, it does work if lists contain other objects (like std::string):
std::list<std::string> s1;
std::list<std::string> s2;
s2.insert(s2.end(), std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()));
Now, if I use another answer from the same question, which uses std::back_inserter and std::move, it works with both std::vector and std::list:
std::list<std::unique_ptr<int>> c1;
std::list<std::unique_ptr<int>> c2;
c1.push_back(std::unique_ptr<int>(new int));
std::move(c1.begin(), c1.end(), std::back_inserter(c2));
As far as I understand, this solution basically moves each item individually when back inserting on the second container.
My question is, why using std::make_move_iterator on a std::list of std::unique_ptr doesn't work but it does with std::vector or if the list element is of a different type?
Note: I'm using Visual Studio 2010.
The core problem is that Visual Studio 2010's implementation of std::list::insert doesn't support moving semantics. Internally, the std::list::insert invokes a method called _Insert, which is declared as follows in VS 2010:
void _Insert(const_iterator _Where, const _Ty& _Val)
In VS 2017 (not checked for other versions), it calls the same method but it is declared as:
void _Insert(_Unchecked_const_iterator _Where, _Valty&&... _Val)
As seen, VS 2017 uses an rvalue reference, therefore calling the moving constructor of std::unique_ptr when making the insertion. On the other hand, VS 2010 uses an lvalue reference instead, so at some moment the copy constructor is called, which is declared private for std::unique_ptr, generating the compilation error.
Conclusion
In VS 2010 there is no way to use the solution based on std::make_move_iterator because how std::list::insert is implemented. Options for appending a std::list<std::unique_ptr<T>> into another one include:
Using the back_inserter:
std::move(c1.begin(), c1.end(), std::back_inserter(c2));
Using std::list::splice (credit to #T.C.), which is very useful since it can be directly used with lists returned by functions:
c2.splice(c2.end(), c1);

VSIX how to order my classifier provider in respect to other installed extension

I developed a toy vsix extension. It implements a classifier for F# source files.
In the meantime the guys from FSharp Power Tools upgraded their extension to offer syntax highlighting for F# files.
Now in VS 2013 my classifier is always run before theirs, and consequently they are overriding my coloring.
Is there a way to order a classifier on respect to another? I did not find any info about this by googling.
Thanks
Unfortunately there is no way to do this. Classification is a form of tagging and tagging is unordered in Visual Studio. The editor simply runs an import for all tagging implementations and essentially defaults to MEF import for ordering.
Many hooks in Visual Studio can be ordered by using the [Order] attribute. This is typically listed as part of the documentation on MSDN. It is not for classification / tagging and I checked the implementation to make sure it wasn't an oversight (it wasn't).
I've figured it out.
In my case Priority.Low has to be specified as Order attribute for the classes that implement ClassificationFormatDefinition.
Actually this solutions works only for 2 classifiers.
FSharp Power Tools has the Order(After = Priority.Default)
My classifier will be invoked after FSharp Power Tools when After = Priority.Low.
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = "FSharpNumberClassifier")]
[Name("FSharpNumberClassifier")]
[UserVisible(true)] //this should be visible to the end user
[Order(After = Priority.Low)]
internal sealed class FSharpNumberClassifierFormat : ClassificationFormatDefinition
Actually I've encountered similar problem. My VSIX extension colorized DSL statements in code via regular expressions. The problem was with the comments in code - it didn't avoid them and writing logic which would analyze all comment-related cases and produce correct tags was quite a lot of work, too much actually. So I've come up with an idea - may be I can rearrange the order of coloring for my coloring to be done before comments and preprocessor instructions. Then these colors will override my incorrect coloring.
I've already googled Order attribute but it didn't work in my case because as far as I remember I couldn't place my classification type in the correct place, it either overrided comments coloring or was overriden by some other default coloring. All I needed was to increase priority of comments and preprocessor definitions to make them override my coloring. It's a hacky decision but it worked for me.
So I've ended up with a following solution. In a class wich initializes yours classification formats (in my case it is tagger provider) I added IClassificationFormatMapService service via MEF. Also I already had IClassificationTypeRegistryService service to get IClassificationType objects
[Import]
internal IClassificationFormatMapService classificationFormatMapService = null;
[Import]
internal IClassificationTypeRegistryService classificationRegistry = null;
For the names of predefined classification types you will need Microsoft.VisualStudio.Language.StandardClassification nuget package.
Then you should add using directive to your file
using Microsoft.VisualStudio.Language.StandardClassification;
Then I used a following code fragment:
private static void IncreaseCommentFormatTypesPrioirity(IClassificationTypeRegistryService registry, IClassificationFormatMapService formatMapService,
IClassificationType myType)
{
IClassificationFormatMap formatMap = formatMapService.GetClassificationFormatMap(category: "text");
IncreaseServiceFormatPriority(formatMap, registry, PredefinedClassificationTypeNames.ExcludedCode, myType);
IncreaseServiceFormatPriority(formatMap, registry, PredefinedClassificationTypeNames.Comment, myType);
}
private static void IncreaseServiceFormatPriority(IClassificationFormatMap formatMap, IClassificationTypeRegistryService registry, string formatName, IClassificationType myType)
{
IClassificationType predefinedClassificationType = registry.GetClassificationType(formatName);
IClassificationType artificialClassType = registry.CreateTransientClassificationType(predefinedClassificationType);
TextFormattingRunProperties properties = formatMap.GetExplicitTextProperties(predefinedClassificationType);
formatMap.AddExplicitTextProperties(artificialClassType, properties, myType);
formatMap.SwapPriorities(artificialClassType, predefinedClassificationType);
formatMap.SwapPriorities(myType, predefinedClassificationType);
}
It works for me. It's an experimental code and there is a lack of documentation on transient classification types and classififcation order, so I'm not 100% (even 90%) sure that it does all things right and doesn't break something in VS.
But, after all you can change the classification order at runtime (although you cannot tell the exact position explicitly, you have to use SwapPriorities method which will change places of two formats)

Visual Studio 2010 Extension - events not called

I trying to hook several Visual Studio events. Unfortunately I am failing in the first step. The event handlers are never called.
So my question is what I am doing wrong?
Here a little excerpt of my code.
// here are some attributes
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExists_string)]
public sealed class VSPackage : Package {
EnvDTE80.DTE2 dte_;
EnvDTE.DocumentEvents documentEvents_;
EnvDTE.WindowEvents windowEvents_;
public VSPackage2Package() {
Trace.WriteLine("I am get called.");
}
protected override void Initialize() {
Trace.WriteLine("I am get called too.");
dte_ = (EnvDTE80.DTE2) System.Runtime.InteropServices.Marshal.
GetActiveObject("VisualStudio.DTE.10.0");
windowEvents_ = dte_.Events.WindowEvents;
documentEvents_ = dte_.Events.DocumentEvents;
windowEvents_.WindowCreated +=
new EnvDTE._dispWindowEvents_WindowCreatedEventHandler(
windowEvents_WindowCreated);
documentEvents_.DocumentOpened +=
new EnvDTE._dispDocumentEvents_DocumentOpenedEventHandler(
documentEvents__DocumentOpened);
Trace.WriteLine("Everything fine until here.");
}
void documentEvents__DocumentOpened(EnvDTE.Document document) {
Trace.WriteLine("Never called");
}
void windowEvents_WindowCreated(EnvDTE.Window window) {
Trace.WriteLine("Never called");
}
}
Edit:
I get it working, looking at other sample code, I figured out that they sometimes getting the DTE object differently. Changing
dte_ = (EnvDTE80.DTE2) System.Runtime.InteropServices.Marshal.
GetActiveObject("VisualStudio.DTE.10.0");
to
dte_ = GetService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;
and now everything is fine.
It should work.
I'm pretty sure that if you do the same from an Addin it would work. Packages can be painfull sometimes.
In fact, when a package is loaded the shell (DTE) may not be fully loaded yet. Try to register your events when it is.
To do so, use the OnShellPropertyChange event and the Zombie state to know when to register.
http://social.msdn.microsoft.com/forums/en-US/vsx/thread/3097a0e1-68e3-47ea-a4ba-8511571b2487/
Read the following, I think it answers your question. Note : The GetService method is the same as calling GetGlobalService.
1. ServiceProvider.GlobalProvider
This new static property on the
ServiceProvider class allows access to
the global service provider from any
code, as long as it is called from the
main UI thread. This property is
closely related to the
Package.GetGlobalService static method
which was available in previous
versions of the MPF. The problem with
Package.GetGlobalService was that it
would fail if a package had not yet
been initialized. This led to subtle
ordering bugs in code that used the
MPF libraries without initializing a
package of their own. Sometimes they
would work only because another
package had already initialized the
global ServiceProvider on their
behalf. If that other package was
uninstalled, or perhaps moved to a
different version of the MPF, that
static would no longer be initialized
causing Package.GetGlobalService to
fail.
Now, in MPF 10, you can call
ServiceProvider.GlobalProvider at any
time as long as you are calling from
the UI thread. For compatibility, this
mechanism will still use the
ServiceProvider created by the first
Package to be sited but, in the case
where no Package has yet been
initialized, MPF 10.0 now has the
ability to obtain the global provider
from the registered COM message
filter. Package.GetGlobalService() is
also hooked up to this new mechanism.
Make sure you are not boxing and unboxing your DTE object. I found this was the issue for me.
See my solution here: http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/eb1e8fd1-32ad-498c-98e9-25ee3da71004

Visual Studio 2010 and Test Driven Development

I'm making my first steps in Test Driven Development with Visual Studio. I have some questions regarding how to implement generic classes with VS 2010.
First, let's say I want to implement my own version of an ArrayList.
I start by creating the following test (I'm using in this case MSTest):
[TestMethod]
public void Add_10_Items_Remove_10_Items_Check_Size_Is_Zero() {
var myArrayList = new MyArrayList<int>();
for (int i = 0; i < 10; ++i) {
myArrayList.Add(i);
}
for (int i = 0; i < 10; ++i) {
myArrayList.RemoveAt(0); //should this mean RemoveAt(int) or RemoveAt(T)?
//VS doesn't know. Any work arounds?
}
int expected = 0;
int actual = myArrayList.Size;
Assert.AreEqual(expected, actual);
}
I'm using VS 2010 ability to hit
ctrl + .
and have it implement classes/methods on the go.
I have been getting some trouble when implementing generic classes. For example, when I define an .Add(10) method, VS doesn't know if I intend a generic method(as the class is generic) or an Add(int number) method. Is there any way to differentiate this?
The same can happen with return types. Let's assume I'm implementing a MyStack stack and I want to test if after I push and element and pop it, the stack is still empty. We all know pop should return something, but usually, the code of this test shouldn't care for it. Visual Studio would then think that pop is a void method, which in fact is not what one would want. How to deal with this? For each method, should I start by making tests that are "very specific" such as is obvious the method should return something so I don't get this kind of ambiguity? Even if not using the result, should I have something like int popValue = myStack.Pop() ?
How should I do tests to generic classes? Only test with one generic kind of type? I have been using ints, as they are easy to use, but should I also test with different kinds of objects? How do you usually approach this?
I see there is a popular tool called TestDriven for .NET. With VS 2010 release, is it still useful, or a lot of its features are now part of VS 2010, rendering it kinda useless?
Whenever I define a new property in my test code, and ask VS to generate that method stub for me, it generates both a getter and a setter. If I have something like int val = MyClass.MyProperty i'd like to to understand that (at least yet) I only want to define a getter.
Thanks
I see there is a popular tool called TestDriven for .NET. With VS 2010 release, is it still useful, or a lot of its features are now part of VS 2010, rendering it kinda useless?
It's still useful in case you use one of a number of different unit testing frameworks (nunit, mbunit, xunit, csunit, etc).
There are also other tools (like Visual Nunit) that provide visual studio integration for running unit tests.
To your code sample, why would you have a method RemoveAt(T obj)?
You can do RemoveAt(int index) and Remove(T obj) instead. Take a look at Microsoft's APIs (for example, for List<T>) that see how they set up the Remove methods for a generic collection.
And now for your points:
1: What would Add(int number) do? If I understand your intentions correctly, Add(10) can only be intepreted as "Add value 10 at the end of my collection". If you wanted to add a value at a particular index, you can (and probably should) name that method Insert: Insert(int index, T value).
2: sure, Visual Studio will interpret the method as void at first, but you can edit it to be something like
public class MyStack<T>
{
public T Pop()
{
}
}
The stubs built by pressing Ctrl+. are a convenience, but not gospel. You don't HAVE to always assign a return value to a variable. If you don't need it in a test, don't do it. If you want VS to pick up on a return type other than void, you can write a different unit test (e.g. that Pop() returns the last pushed value).
3: I'd test with the types that I see most frequently used in my code. If you're writing a public API, then test with as many types as possible. If you're using NUnit, look into using the [TestCase] attribute to help you avoid writing some duplicate code.
4: I still use TestDriven, but I haven't tried going without it, so I can't really make a useful comparison.
5: Just delete the setter if you don't need it. Some addon frameworks like ReSharper support more advanced code generation, including read-only properties.

Resources