is there some way to autogenerate the obvious 2-param constructor for this class in visual studio?
class Thing {
public readonly string a;
public readonly Object b;
}
I guess you're supposed to use the:
new Thing { a = ..., b = ... }
syntax in such cases, but that won't work with readonly fields as above. Another plus of having a constructor is that you can't forget a field.
There is, Resharper supports this functionality. You choose the "generate constructor", pick the fields you want included and you've got your constructor.
Sorry for a post that's not helpful at all, but I just couldn't resist.
I'm afraid that by using things like T4 templates, you'll (probably) lose IntelliSense, which may not be a price you wanted to pay. You could probably write a VS.NET macro to auto-generate code of the constructor (I believe the code model should give you enough information to do that).
Now, here is the useless part of the post - perhaps you could try another .NET language if you're annoyed with the unnecesary verbosity of C#. In F#, you can write implicit constructors and their parameters automatically become (readonly) fields:
type Thing(a:string, b:Object) =
// members can use 'a' and 'b' directly - here is one example:
member this.GetInfo() =
"Some info: " + a + (b.ToString())
In a real-world scenario, you probably wouldn't need to specify the types, because F# could infer them automatically based on the later usage. Experimenting with F# isn't as difficult if you're already familiar with .NET libraries.
You may want to look at T4 templates. It would be fairly simple to write a template which iterates a list of the readonly property names and types and creates the necessary code for the properties and constructor.
T4 templates are built into Visual Studio. Check out Scott Hanselman's blog about T4 templates for more detail.
There are other products which can automate this kind of refactoring. Resharper is one of these, but it is not free.
Related
I have many Model-Classes which implement the INotifyPropertyChanged-Interface in order to update the UI when value changed.
Sadly the properties must be written fully to support this feature. I decreased my code already by using the 'SetPropertyValue'-Method() in BaseClass.
private string _title;
public string Title
{
get { return title; }
set { SetPropertyValue("Title", ref _title, value ); }
}
But with 20 properties written like that in one file it is not so simple to understand the content of the file in a short time unlike to the auto implemented properties.
What I want is to write my Property like this:
[NotifyChanged]
public string Title { get; set; }
I checked already PostSharp but in the free version there are only 10 classes included (it's a hobby project so I don't want to pay much money).
Is there any possibility to attach my one logic to C#-Compiler (as a pre-compiler)?
Such a feature I would like to use on different places in my code to reduce unneccessary coding lines (especially for auto-properties).
Or maybee a VisulStudio-Extension?
Try Fody. It is library which modifies IL code during build process using dedicated msbuild task.
It has large base of addins including PropertyChanged which should suit in your scenario.
This addin gives you attribute ImplementPropertyChanged which you can apply to a class. Then Fody will generate code implementing INotifyPropertyChanged to all auto-properties.
Second option if you have ReSharper version 7 or higher. It has refactoring which can help you with implementation of INotifyPropertyChanges. For example it can transform auto-property to "normal" property implementing the interface.
Thou it may not fully satisfy you - this approach may be interesting for you because it does not involve additional libraries and assembly modification.
Another option is Castle DynamicProxy. The difference between PostSharp and Fody is that DynamicProxy generates its proxies on the fly at runtime.
Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.
When one choose Refactoring, Encapsulate Fields for let's say:
int m_member;
VS will generate
public int Member
{
get { return m_member; }
set { m_member = value; }
}
For some reason (using a reverse engineerint tool for example which doesn't know this style), I'd like to get the oldish and more verbose style:
public int getMember() {
return m_member;
}
public void setMember(int value) {
m_member = value;
}
Is it possible to configure VS to do so ? Otherwise any other mean with sample code like creating snippet template or even Plugin if necessary ?
Although I don't necessarily recommend this, all refactorings are simply snippets that you can edit. A default installation will put the C# templates in this folder, C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring, simply find the one that you want and modify as you see fit.
NOTE: Be sure to take a backup first!!
I'll also agree with everyone else, that this is a REALLY bad idea!
So... you want to write Java/C++/(any language that doesn't support properties) in C#? Why?
Properties are nice because:
Syntax is cleaner.
Debugging is easier (you can see the value in the debugger as if the property were a field).
It is idiomatic. C# developers will furrow their brow at you when they look at your code. Yes, this does sometimes matter, and it certainly matters if you are not the sole developer working on this project.
Even your method naming convention looks like Java. It is a good idea to get into the habit of adopting the idioms of a new language as you learn it.
This pattern is not idiomatic of C# code - and Visual Studio doesn't support it. I would recommend avoiding it in favor of the property syntax. However, if you really do need it for some reason, you can get there with ReSharper. Here's what you do in ReSharper:
Refactor >> Encapsulate Field (this creates a property)
Refactor >> Convert >> Property To Method(s) (this generates the get/set methods)
The first step let's you create a property that wraps the public field.
The second replaces that property with get/set methods whose names you can specify.
I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.
So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to strongly discourage normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to advertise that there is a way to do something wrong.)
It would be nice to be able to tell Intellisense to not show the function, for instance.
The best solution I have at the moment is to just name the function something like: DangerousSet().
What other options do I have?
Follow-Up
I found Amy B's answer most useful to my situation. Thanks!
Mufasa's suggestion to use reflection was great, but harder to implement (for me).
Chris' suggestion of using a decorator was good, but didn't pan out.
BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.
Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.
You can use InternalsVisibleToAttribute to mark internal members as visible to your test assembly. It seems to shine when used in this context, though its not quite "friend".
Mark your DangerousSet function internal instead of public.
In Properties\AssemblyInfo.cs of the project containing DangerousSet:
[assembly:InternalsVisibleTo("YourTestAssembly")]
If you have two test assemblies for whatever reason, the syntax is:
[assembly:InternalsVisibleTo("TestAssembly1"),
InternalsVisibleTo("TestAssembly2")]
Decorate your method with this attribute:
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
This will hide it from Intellisense.
EDIT:
But apparently this has a rather significant caveat: "In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly." Via MSDN.
Suppose you want to test this object by manipulating its fields.
public class ComplexCalculation
{
protected int favoriteNumber;
public int FavoriteNumber
{
get { return favoriteNumber; }
}
}
Place this object in your test assembly/namespace:
public class ComplexCalculationTest : ComplexCalculation
{
public void SetFavoriteNumber(int newFavoriteNumber)
{
this.favoriteNumber = newFavoriteNumber;
}
}
And write your test:
public void Test()
{
ComplexCalculationTest myTestObject = new ComplexCalculationTest();
myTestObject.SetFavoriteNumber(3);
ComplexCalculation myObject = myTestObject;
if (myObject.FavoriteNumber == 3)
Console.WriteLine("Win!");
}
PS: I know you said internal, but I don't think you meant internal.
It sounds like your real problem is in your reference documents. You shouldn't test cases that are impossible to encounter under proper use of your class. If users shouldn't be allowed to change the state of those variables, then neither should your tests.
You can also use reflection. Google search turned up Unit testing private methods using reflection.
Can your test code include a subclass of the calculations class? If so, you can mark the function protected and only inheritors will be able to use it. I'm pretty sure this also takes it out of intellisense, but I could be wrong about that.
What I've done in the past is I put XML Comments by the method and used the section to write in big bold letters. DON'T USE THIS METHOD or whatever. That way, if someone tried to use it, Intellisense would give them a nice warning.
I've thought of this before and it came to mind again when reading this question.
Are there any plans for "extension properties" in a future version of C#?
It seems to me they might be pretty stright-forward to implement with a little more "compiler magic". For example, using get_ and set_ prefixes on extension method names would turn that method into an extension property:
public class Foo
{
public string Text { get; set; }
}
public static class FooExtensions
{
public static string get_Name(this Foo foo)
{
return foo.Text;
}
public static void set_Name(this Foo foo, string value)
{
foo.Text = value;
}
}
Are there any technical restrictions which would prevent this? Would this create too much stuff going on behind the scenes? Not important enough to be worth the effort?
The official site for feature requests is http://connect.microsoft.com/VisualStudio.
There has already been a request for extension properties here.
Microsoft's answer on 7/29/2008 included the following:
Extension properties are a common
request, and we actually got quite far
with a design for the next version of
the language, but ultimately had to
scrap it because of various
difficulties. It is still on our
radar.
Generally I think this would encourage poor practice.
Properties are supposed to represent some kind of state about the object in question, whereas methods should represent units of work. But many developers tend to put computationally intensive or relatively long-running code in the getters and setters where they would be much more appropriate as methods.
Extending an object is not the same as deriving from it. If you need to add properties, from a philosophical perspective you're talking about needing to add stateful information to the object. That should be done by deriving from the class.
Although I don't think what you're proposing is a good idea, you can get pretty much the same thing with the upcoming dynamic type in C# 4. Part of what is planned is to allow new properties and methods to be added at runtime to existing objects and types. One difference is that you won't have the compile-time checking of an extension property.
There might be something to be said about that kind of trick.
Just look at Attached properties in WPF. They do give tremendous power for declarative behavior attachment. But I'm not sure what that would look like outside of a declarative context...
I'm not sure how that would work. Extensions have to be static, so the property itself would have to static. The means whatever you use to back these properties would also be static. But expect your planned use for these expects them to be associated with the instances indicated by the this keyword rather than the type itself.
"Extension properties" are available today via inheritance. Adding such a beast would encourage poor oop practices and generaly be more trouble than its worth.