Just to confirm there isn't a way to avoid hard-coded values in c# attributes right?
[SomeAttribute(3+1)]
public void Foo(string s)
or access class members or do anything not precompiled?
I now explore the great example of retry mechanism in postsharp - and would like to see if I can configure the number of retries from outside the system
Attribute constructor arguments and property values are baked into the compiled code. They can't be determined at execution time.
Of course, if you have attribute which is willing to play ball, you could give it (say) a type and the name of a property, and ask it to fetch that property value at execution time. (That's what NUnit does for [TestCaseSource], for example.) But you can't do this with an attribute which doesn't know to do so.
Related
I am possibly asking the impossible but I shall ask anyway. From the following:
public SomeClassConstructor(SomeOtherClass someOtherClass, string someString){
...
}
Is it possible to access the arguments so that they can be iterated (for example some sort of reflection to access an IEnumerable<object> that contains the arguments)?
Note: The params[] collection is not an answer in this situation. Other restrictions are that this is to be used in a WinForms environment; .Net 4.5 is acceptable.
EDIT: In response to DavidG's comment I am after the objects themselves (aka values and names). The reason being that I have a requirement to log (serialized) the arguments when a form is opened (when a UAT flag is set in app.config!). Large objects have their serialization over ridden to return simple strings so as not to bloat in memory.).
No, you can't access parameter values via reflection. You can get the names, types, attributes etc - but not the values. That's true of methods, constructors, property setters, indexers etc.
You could potentially do it in a debugger API, but that's almost never the right approach.
For logging, you should either just do this manually:
Log("someOtherClass={0}, someString={1}", someOtherClass, someString);
or look into AOP to inject calls automatically - look at PostSharp for example.
Assume that 2 different methods - one static and one non-static - need an instance variable.
The variable is used 3-5 different times within the methods for comparison purposes.
The variable is NOT changed in any manner.
Also would the type of variable - String, Colection, Collection, etc. make any difference on how it should be coded.
What is the best/right way of using Instance Variable within a private method (static and non-static)?
Pass as method argument
Store locally by using the method to get the value - this.getClaimPropertyVertices();
Store locally by getting the value - this.claimPropertyVertices;
Use the instance variable directly in the method
When creating a local variable to store the value will the "final" keyword provide any advantages, if the variable will not be changed.
Edit 1: Based on a comment, I am adding additional information
The value cannot be created locally in the method. It has to come from the class or some other method accessed by the class.
My Solution Based on the Answers:
Based on the answer by #EricJ. and #Jodrell. I went with option 1 and also created it as a private static method. I also found some details here to support this.
When creating a local variable to store the value will the "final" keyword provide any advantages, if the variable will not be changed
In Java, final provides an optimization opportunity to the compiler. It states that the contents of the variable will not be changed. The keyword readonly provides a similar role in C#.
Whether or not that additional opportunity for optimization is meaningful depends on the specific problem. In many cases, the cost of other portions of the algorithm will be vastly larger than optimizations that the compiler is able to make due to final or readonly.
Use of those keywords has another benefit. They create a contract that the value will not change, which helps future maintainers of the code understand that they should not change the value (indeed, the compiler will not let them).
What is the best/right way of using Instance Variable within a private method (static and non-static)?
Pass as method argument
The value is already stored in the instance. Why pass it? Best case is this is not better than using the instance property/field. Worst case the JITer not inline the call, and will create a larger stack frame costing a few CPU cycles. Note: if you are calling a static method, then you must pass the variable as the static method cannot access the object instance.
Store locally by using the method to get the value - this.getClaimPropertyVertices();
This is what I do in general. Getters/setters are there to provide a meaningful wrapper around fields. In some cases, the getter will initialize the backing field (common pattern in C# when using serializers that do not call the object constructor. Don't get me started on that topic...).
Store locally by getting the value - this.claimPropertyVertices;
No, see above.
Use the instance variable directly in the method
Exactly the same as above. Using this or not using this should generate the exact same code.
UPDATE (based on your edit)
If the value is external to the object instance, and should not meaningfully be stored along with the instance, pass it in as a value to the method call.
If you write your functions with the static keyword whenever you can, there are several obvious benefits.
Its obvious what inputs effect the function from the signature.
You know that the function will have no side effects (unless you are passing by reference). This overlooks non-functional side effects, like changes to the GUI.
The function is not programtically tied to the class, if you decide that logically its behaviour has a better association with another entity, you can just move it. Then adjust any namespace references.
These benefits make the function easy to understand and simpler to reuse. They will also make it simpler to use the function in a Multi Threaded context, you don't have to worry about contention on ever spreading side effects.
I will cavet this answer. You should write potentially resuable functions with the static keyword. Simple or obviously non-resulable functionality should just access the private member or getter, if implemented.
My answer to one of the question on SO was commented by Valentin Kuzub, who argues that inlining a property by JIT compiler will cause the reflection to stop working.
The case is as follows:
class Foo
{
public string Bar { get; set; }
public void Fuzz<T>(Expression<Func<T>> lambda)
{
}
}
Fuzz(x => x.Bar);
Fuzz function accepts a lambda expression and uses reflection to find the property. It is a common practice in MVC in HtmlHelper extensions.
I don't think that the reflection will stop working even if the Bar property gets inlined, as it is a call to Bar that will be inlined and typeof(Foo).GetProperty("Bar") will still return a valid PropertyInfo.
Could you confirm this please or my understanding of method inlining is wrong?
JIT compiler operates at runtime and it can't rewrite metadata information stored in the assembly. And reflection reads assembly to access this metadata. So there are no impact from JIT-compiler to reflection.
EDIT:
Actually there are couple of places when C# compiler itself "inlines" some information during compilation. For example, constants, enums and default arguments are "inlined" so you can't access them during reflection. But it definitely not related to your particular case.
Yeah when I think about it more I guess only way inlining properties could fail INotifyPropertyChanged interface correct work would be if you were using a reflection based method used like
public Count
{
get {return m_Count;}
set { m_Count=value;
GetCurrentPropertyNameUsingReflectionAndNotifyItChanged();}
}
If used like you suggest indeed metadata exists in assembly and property name will be successfully taken from there.
Got us both thinking though.
I personally agree with #Sergey:
Considering that inlining happens on JIT compiler side, but metadata generated before, it shouldn't inpact on reflection in any way. By the way, good question, like it +1
Expression trees can't be in-lined anyway since they are a representation of the expression (abstract syntax tree) rather than the expression itself.
Delegates, even if they can be in-lined, will still carry the data about the method and target being called in their properties.
I am working on a project using ReSharper. On occasion it prompts me that a field can be made readonly. Is there any performance or other benefit to this? I am presuming the benefits would be quite low-level, or would any benefits be purely semantic?
Thanks
With example below the field was initially just private, but resharper prompted to set it as readonly. I understand the reason why it can be set as readonly, ie. its being set in the constructor and not changed again, but just wondering if there are any benefits to this...
public class MarketsController : Controller
{
private readonly IMarketsRepository marketsRepository;
public AnalysisController(IMarketsRepository marketsRepository)
{
this.marketsRepository = marketsRepository;
}
}
Edit
What is the easiest way to look at the MSIL?
The benefit is purely semantic. It will help users of your code explicitly understand that this field can't be changed after object is created. Compiler will prevent unwanted changes of this field. I totally agree with following quote from Python Zen:
Explicit is better than implicit.
Some details:
The only difference between normal field and read-only field is flag initonly in IL. There is no optimization about it (as with constants) because actually it allows all operations (get and set, but only in ctor). It is just hint to compiler: don't let it be changed after construction.
.field public initonly int32 R
It's not so much low-level performance, but more high-level maintainability. Making things readonly is one of the possibilities you have to limit and control the number of places a certain value can be changed. This in turn means that you reduce interdependency between classes (a.k.a. "loose coupling"); the result is an application that has fewer internal dependencies and thus a lower complexity. In other words, readonly fields and properties make your application more maintainable.
It also might help spotting some bugs as well. The value is assigned in a construcotor only and this could be a problem if you forgot to change elsewhere or not. And if it is not supposed to be changed then you mark it as a read only.
My professor taught me back in the day that declaring something readonly is a way of admitting to your computer that you make mistakes.
You might be interested in this answer.
The readonly keyword is used to
declare a member variable a constant,
but allows the value to be calculated
at runtime. This differs from a
constant declared with the const
modifier, which must have its value
set at compile time. Using readonly
you can set the value of the field
either in the declaration, or in the
constructor of the object that the
field is a member of.
I'm trying to formalise the usage of the "out" keyword in c# for a project I'm on, particularly with respect to any public methods. I can't seem to find any best practices out there and would like to know what is good or bad.
Sometimes I'm seeing some methods signatures that look like this:
public decimal CalcSomething(Date start, Date end, out int someOtherNumber){}
At this point, it's just a feeling, this doesn't sit well with me. For some reason, I'd prefer to see:
public Result CalcSomething(Date start, Date end){}
where the result is a type that contains a decimal and the someOtherNumber. I think this makes it easier to read. It allows Result to be extended or have properties added without breaking code. It also means that the caller of this method doesn't have to declare a locally scoped "someOtherNumber" before calling. From usage expectations, not all callers are going to be interested in "someOtherNumber".
As a contrast, the only instances that I can think of right now within the .Net framework where "out" parameters make sense are in methods like TryParse(). These actually make the caller write simpler code, whereby the caller is primarily going to be interested in the out parameter.
int i;
if(int.TryParse("1", i)){
DoSomething(i);
}
I'm thinking that "out" should only be used if the return type is bool and the expected usages are where the "out" parameters will always be of interest to the caller, by design.
Thoughts?
There is a reason that one of the static code analysis (=FxCop) rules points at you when you use out parameters. I'd say: only use out when really needed in interop type scenarios. In all other cases, simply do not use out. But perhaps that's just me?
This is what the .NET Framework Developer's Guide has to say about out parameters:
Avoid using out or reference parameters.
Working with members
that define out or reference
parameters requires that the developer
understand pointers, subtle
differences between value types and
reference types, and initialization
differences between out and reference
parameters.
But if you do use them:
Do place all out parameters after all of the pass-by-value and ref
parameters (excluding parameter
arrays), even if this results in an
inconsistency in parameter ordering
between overloads.
This convention makes the method
signature easier to understand.
Your approach is better than out, because you can "chain" calls that way:
DoSomethingElse(DoThing(a,b).Result);
as opposed to
DoThing(a, out b);
DoSomethingElse(b);
The TryParse methods implemented with "out" was a mistake, IMO. Those would have been very convenient in chains.
There are only very few cases where I would use out. One of them is if your method returns two variables that from an OO point of view do not belong into an object together.
If for example, you want to get the most common word in a text string, and the 42nd word in the text, you could compute both in the same method (having to parse the text only once). But for your application, these informations have no relation to each other: You need the most common word for statistical purposes, but you only need the 42nd word because your customer is a geeky Douglas Adams fan.
Yes, that example is very contrived, but I haven't got a better one...
I just had to add that starting from C# 7, the use of the out keyword makes for very readable code in certain instances, when combined with inline variable declaration. While in general you should rather return a (named) tuple, control flow becomes very concise when a method has a boolean outcome, like:
if (int.TryParse(mightBeCount, out var count)
{
// Successfully parsed count
}
I should also mention, that defining a specific class for those cases where a tuple makes sense, more often than not, is more appropriate. It depends on how many return values there are and what you use them for. I'd say, when more than 3, stick them in a class anyway.
One advantage of out is that the compiler will verify that CalcSomething does in fact assign a value to someOtherNumber. It will not verify that the someOtherNumber field of Result has a value.
Stay away from out. It's there as a low-level convenience. But at a high level, it's an anti-technique.
int? i = Util.TryParseInt32("1");
if(i == null)
return;
DoSomething(i);
If you have even seen and worked with MS
namespace System.Web.Security
MembershipProvider
public abstract MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status);
You will need a bucket. This is an example of a class breaking many design paradigms. Awful!
Just because the language has out parameters doesn't mean they should be used. eg goto
The use of out Looks more like the Dev was either Lazy to create a type or wanted to try a language feature.
Even the completely contrived MostCommonAnd42ndWord example above I would use
List or a new type contrivedresult with 2 properties.
The only good reasons i've seen in the explanations above was in interop scenarios when forced to. Assuming that is valid statement.
You could create a generic tuple class for the purpose of returning multiple values. This seems to be a decent solution but I can't help but feel that you lose a bit of readability by returning such a generic type (Result is no better in that regard).
One important point, though, that james curran also pointed out, is that the compiler enforces an assignment of the value. This is a general pattern I see in C#, that you must state certain things explicitly, for more readable code. Another example of this is the override keyword which you don't have in Java.
If your result is more complex than a single value, you should, if possible, create a result object. The reasons I have to say this?
The entire result is encapsulated. That is, you have a single package that informs the code of the complete result of CalcSomething. Instead of having external code interpret what the decimal return value means, you can name the properties for your previous return value, Your someOtherNumber value, etc.
You can include more complex success indicators. The function call you wrote might throw an exception if end comes before start, but exception throwing is the only way to report errors. Using a result object, you can include a boolean or enumerated "Success" value, with appropriate error reporting.
You can delay the execution of the result until you actually examine the "result" field. That is, the execution of any computing needn't be done until you use the values.