I do not understand the difference between get_Offset and Offset:
MSDN on NamedRange.get_Offset states
This API supports the Visual Studio infrastructure and is not intended
to be used directly from your code. Use the Offset property instead of
this method.
What does that mean exactly? Similar is also said for get_Value method which is widely used directly in code.
Take following examples which would do the same for me.
myRange.get_Offset(1,0).Value = "Foo";
myRange.Offset[1,0].Value = "Foo";
What are their difference?
get_Something
is an internal function that generates by the CLR for property get accessor.
For example if you have a property
public string Name {get;set;}
after compilation you will find a
get_Name and set_Name methods, cause the properties are nothing then simple wrappers over the set-variable/get-variable concept in a single class domain.
Being an internal method, it's not good practise to make use of it, it's better to use a user defined, clear property access.
get_Offset can theoretically be changed or removed without warning. If the documentation says to use another equivalent method you should do just that.
get_Value is only marked that way for Visual Studio 2005 so you can use that freely
The difference is exactly as the documentation says. You should use the Offset property, not the get_Offset method.
The method is just public because they needed it to be accessible in that way for some other class. The method may just go away in any future version if they find a better way to use the class, and it won't even be mentioned as a breaking change as the documentation clearly states that you shouldn't use it.
Related
I've been working in C for the past couple of years and I've managed to get use to putting single-purpose, static variables near where they are used within my code.
While writing a very basic method that was in need of a method-scope static value, I was a bit surprised to find that the compiler didn't like that I tried to define a static object from within my method.
Googling has verified that this isn't possible within C#. Still, I'm curious why code, like the following, is completely off limits.
public int incrementCounterAndReturn()
{
static int i = 0;
return ++i;
}
Granted, this is a simplistic example that could be redefined for the same affect but that's beside the point. Method-scope, static values have their place and purpose. What design decisions have prevented such an implementation of static objects within C#?
We're on C# version 5.0 and it's 2013. I can only assume this isn't possible because of a design choice and not just because "that's complex and hard stuff to implement." Does anyone have any insider information?
The language design team is not required to provide a reason to not implement a feature. Rather, the person who wants the feature is required to make the case that the feature is the best possible way the design, implementation, test, and education teams can be spending their budgets. No one has ever successfully done so for your proposed feature.
Were I still on the design team and had this feature pitched I would point out that it is completely unnecessary. The feature in C is a known cause of developer confusion, particularly for novices, and the benefit of local vs type scope is tiny.
The underlying runtime does not provide method level static variables. In the CLR, all "static" data is defined on the type level, not method level. C# decided to not add this at the language level in its language design.
This is purely a design choice. VB.Net, which compiles to the same IL, does allow this via the Shared keyword in a Function or Sub statement (though it's handled via the compiler "promoting" the variable to a class level static variable).
Because in the CLR, static variables are associated with the TYPE. Storage for them is tied to the Type (class or stuct) they are associated with.
static variables are scoped to the class, not to an object instance. To make this work, your method must be declared static, and I believe your class must also be static (since instantiation is not relevant).
But the variable itself must be declared at the class level. C# doesn't allow you to create method-local static variables.
Worth noting: these kinds of maneuvers make it very difficult to unit test the method properly. Normally in C# one would make an ordinary class to hold such state; in fact, that's exactly how yield return works behind the scenes.
The .NET framework and languages were designed around the concept that anyone who is going to be compiling an assembly should be considered trustworthy enough to have access to all the code therein. From a semantic point of view, declaring a static variable foo within method bar would be equivalent to declaring a private static variable outside the method and accessing it within the method, provided only that one chooses as a name something which isn't used anywhere else. If one by convention combines the method name and meaning (e.g. bar_foo) one can generally avoid naming collisions pretty easily. Since the semantics are equivalent to having the variable declared outside the method, there's no need to have it declared inside.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between Property and Field in C#
I thought that basic properties ({ get; set; }) where the same as public fields, with only the advantage of being able to change them without breaking binary compatibility. Following the answer I got here https://stackoverflow.com/a/8735303/331785, I found out there is also a disadvantage to properties. They cannot be accessed by reference if they are of a value type. Why is this, and what other differences are there?
I found out there is also a disadvantage to properties. They cannot be accessed by reference if they are of a value type. Why is this
Because under the covers, a property is just a method. If you look at the IL, you'll see methods like get_PropertyName and set_PropertyName. The problem with that is in order to support working with references, you would need to be able to return a reference for a method.
public ref T MyProperty
{
get
{
return ref _underlyingField;
}
}
Update: Starting in C# 7.0, this is possible using the syntax describe above.
Remainder of previous answer:
This of course, is something entirely possible in the CLR; but not exposed by the C# language.
Though it is possible, the CLR needs some tweaks to keep it as verifiable. The syntax for the property would have to support it to.
However, is any of that useful? As you stated, a field can do it. If you need it; use a field. Supporting it would take a lot of work. There are probably a very few cases where it is appropriate; and would create many cases where just using a field might have been better in the first place.
Properties are just sugar-coating syntax for a getX() and setX() method. It looks and acts like a field, but it's really just two methods. The reason why the auto-property was added was to avoid the repetition of having to create a field and creating a standard getter and setter for the property, and to make it much simpler to allow changing the implementation without changing the interface.
The reason they can't be accessed by reference if they are a value type is because value types are generally on the stack and because you're just calling a method. The getter in the property has to be called and the returned value has to be pushed on the stack before it can be referenced.
In C++, you can define a constant method like so:
int func_that_does_not_modify_this(int arg) const {}
Placing const at the end of the function prevents you from accidentally modifying any of the internal properties, and lets the caller know that this function won't modify the object.
Is there a concept like this in C#?
No, there's nothing like that in C#. It's been talked about a lot, but it's quite difficult to make const work in such a way that it's verifiable at compile time, can't be cast away like it can in C++, and is still reasonably easy to actually use without everyone having to get it perfectly right when they design their own classes.
Of course, if you design your own types to be immutable (like string) then all instance methods on it are effectively const. This isn't always practical, but it's an important technique to use where appropriate.
Code Contract should provide such a feature in the future. Currently, you can mark a method as [Pure], which means it doesn't have any side-effects (i.e. doesn't modify any of the class members). Unfortunately, the current version of the tools does not enforce this rule, so using that attribute is for documentation purpose only. I'm pretty sure that in future version, it will be enforced via static-analysis (i.e. at compile-time), or at least that's what the documentation hints at.
Related SO questions: Pure functions in C#
No. There's nothing similar in C#.
No const & either.
As Jon points out you can obviously implement a const method, but there's no way beyond documentation to let the caller know that a method is const.
C# 8.0 adds support for C++ style const methods, but only to structs. You can add a readonly modifier to a method deceleration to make any modifications to state within it a compiler warning (which you can define as an error if you wish). A readonly struct method may still call a non-readonly method, but that method will be called on a copy of the struct to prevent any changes to the original data.
For more information:
📄 What's new in C# 8.0 | Readonly members
📄 Structure types (C# reference) | readonly instance members
▶️ What's new in C# 8 - Part 2 | Read Only Members
If I am accessing a member field, property, or method, I'm never sure when I should prepend it with 'this'.
I am not asking about cases where it is required, like in the case where a local variable has the same name. I am talking about cases where the meaning is exactly the same. Which is more readable? Are there any standards, best practices, or rules of thumb I should be following? Should it just be consistent throughout a class, or an entire code base?
I disagree with StyleCop on this one, and I'm not even sure that StyleCop's opinion should be interpreted as an official Microsoft guideline anyway. It was an internal tool used at Microsoft but not all teams use it, and not all teams use all the rules.
Adding this everywhere is not necessary and often just adds clutter. It does not improve performance and I'm not convinced that adding this all over the code improves readability either.
You might hear arguments that it makes it more clear where the variable is defined, but I would argue that if your class/method is so long and complicated that it is difficult to work out where something is declared then you probably should refactor it anyway. If you use the single responsibility rule and have short functions it should be obvious whether a variable is a member, a function parameter or a local variable.
As you point out, sometimes it is necessary. For example in the constructor if you want to set a private member with the same name as the parameter.
public class Foo
{
private Bar bar;
public Foo(Bar bar)
{
this.bar = bar;
}
}
I recommend using Microsoft's guidelines, as verified by StyleCop: http://blogs.msdn.com/sourceanalysis/
The general rule is, prepend members with "this." when they are defined in the class, unless they are static, in which case you cannot.
Here is the rule directly from StyleCop:
SA1101: The call to {method or property name} must begin with the
'this.' prefix to indicate that the item is a member of the class.
I would say avoid as much as possible, it saves you some(in fact a lot of) typing.
I would depend on Visual Studio more to help me to find where what belongs(never forget F12). I don't use notepad to read my cs files :P
If you follow Microsoft's StyleCop, you should always use prefix class members with the this keyword.
SA1101: PrefixLocalCallsWithThis
TypeName: PrefixLocalCallsWithThis
CheckId: SA1101 Category: Readability Rules
Here's a similar StackOverflow question on the same topic.
I usually access parameters on the current object with this. Given a naming convention for instance variables "m_", this makes it easy to see at a glance what is affected by following statements without knowing their context:
m_Height += 10; // an instance variable
height += 10; // a local variable
this.Height += 10; // a property
In my code, I only use this.<PropertyName> when the property is a member of a base class, not the class I'm currently in.
Of course, not using 'this' at all is another popular choice, since it's unnecessary code being added.
Our coding standards at work state that member variables shouldn't be prefixed with 'm' or'_' or whatever else most people use. I've actually found myself using this.memberVariable all the time. I prefer the clarity over a little extra typing. And as mentioned in other answers, it's necessary when referencing parameters with the same name as member variables.
If you're using Visual Studio and Intellisense. When you type this you get a list of just your class level variables methods etc. Leaving out all the other possible items.
What is their use if when you call the method, it might not exist?
Does that mean that you would be able to dynamically create a method on a dynamic object?
What are the practical use of this?
You won't really be able to dynamically create the method - but you can get an implementation of IDynamicMetaObject (often by extending DynamicObject) to respond as if the method existed.
Uses:
Programming against COM objects with a weak API (e.g. office)
Calling into dynamic languages such as Ruby/Python
Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g. document.RootElement.Person[5].Name["Attribute"]
No doubt many more we have yet to think of :)
First of all, you can't use it now. It's part of C#4, which will be released sometime in the future.
Basically, it's for an object, whose properties won't be known until runtime. Perhaps it comes from a COM object. Perhaps it's a "define on the fly object" as you describe (although I don't think there's a facility to create those yet or planned).
It's rather like a System.Object, except that you are allowed to call methods that the compiler doesn't know about, and that the runtime figures out how to call.
The two biggies I can think of are duck typing and the ability to use C# as a scripting language in applications, similar to javascript and Python. That last one makes me tear up a little.
Think of it as a simplified form of Reflection. Instead of this:
object value = GetSomeObject();
Method method = value.GetType().GetMethod("DoSomething");
method.Invoke(value, new object[] { 1, 2, 3 });
You get this:
IDynamicObject value = GetSomeObject();
value.DoSomething(1, 2, 3);
I see several dynamic ORM frameworks being written. Or heck write one yourself.
I agree with Jon Skeet, you might see some interesting ways of exploring objects.
Maybe with selectors like jQuery.
Calling COM and calling Dynamic Languages.
I'm looking forward to seeing if there is a way to do a Ruby-like missing_method.