What is new() function here? - c#

I've been learning design patterns and I saw such a method call from a class :
class Client: SubjectAccessor {
static void Main() {
Console.WriteLine("Proxy Pattern\n");
ISubject subject = new Proxy();
Console.WriteLine(subject.Requesy());
subject = new(); //Here is what I am asking
COnsole.WriteLine(subject.Request());
}
}
As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.
Your help is much appreciated.
If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.
Thanks.

It is a typo in the book. There is no current version of C# in which that is valid (it should raise a "Type expected" compiler error). Without context it is impossible to know what it should be.

AFAIK it's wrong, and that code won't even compile.
The new keyword in C# can have only the 3 meanings described in this link:
http://msdn.microsoft.com/en-us/library/51y09td4%28v=VS.80%29.aspx

I was the technical editor of that book; I have a copy right in front of me now. My copy says:
class Client : SubjectAccessor {
static void Main() {
Console.WriteLine("Proxy Pattern\n");
ISubject subject = new Proxy();
Console.WriteLine(subject.Request());
Console.WriteLine(subject.Request());
ProtectionProxy subject = new ProtectionProxy();
Console.WriteLine(subject.Request());
Now, there is an error here; the variable "subject" has been declared twice. Apparently I did not catch the error when I reviewed the book. (The correct thing to do here is to remove the type from the second declaration of "subject").
However, that is not the error that you are reporting.
Are you sure that is not what your copy says? I have the December 2007 first edition; what edition do you have? Perhaps someone attempted to correct this error in a later edition and messed it up? My guess would be that someone tried to correct the error by removing both mentions of the ProtectionProxy type from the erroneous line rather than removing the first one.

That would be the proxy class. never seen such syntax before tho. Best not to use such things as it will only reduce readability..

I can't see how that compiles. "new" in this context is the new operator and this always expects a typename per C# syntax.

Related

C# possible null pointer exception [duplicate]

Here is a piece of code:
IUser user = managerUser.GetUserById(UserId);
if ( user==null )
throw new Exception(...);
Quote quote = new Quote(user.FullName, user.Email);
Everything is fine here. But if I replace "if" line with the following one:
ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);
where function implementation is following:
public abstract class ComponentException<T> : ComponentException
where T : ComponentException, new()
{
public static void FailIfTrue(bool expression, string message)
{
if (expression)
{
T t = new T();
t.SetErrorMessage(message);
throw t;
}
}
//...
}
Then ReSharper generates me a warning: Possible 'System.NullReferenceException' pointing on 1st usage of 'user' object.
Q1. Why it generates such exception? As far as I see if user==null then exception will be generated and execution will never reach the usage point.
Q2. How to remove that warning? Please note:
1. I don't want to suppress this warning with comments (I will have a lot of similar pieces and don't want to transform my source code in 'commented garbage);
2. I don't want to changes ReSharper settings to change this problem from warning to 'suggestion' of 'hint'.
Thanks.
Any thoughts are welcome!
P.S. I am using resharper 5.1, MVSV 2008, C#
Resharper only looks at the current method for its analysis, and does not recursively analyse other methods you call.
You can however direct Resharper a bit and give it meta-information about certain methods. It knows for example about "Assert.IsNotNull(a)", and will take that information into account for the analysis. It is possible to make an external annotations file for Resharper and give it extra information about a certain library to make its analysis better. Maybe this might offer a way to solve your problem.
More information can be found here.
An example showing how it's used for the library Microsoft.Contracts can be found here.
A new answer in old post...
Here a little sample of my code regarding how to use CodeContract via ContractAnnotation with Resharper:
[ContractAnnotation("value:null=>true")]
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
It is very simple...if u find the breadcrumb in the wood. You can check other cases too.
Have a nice day
Q1: Because Resharper doesn't do path analysing. It just sees a possible null reference and flags that.
Q2: You can't without doing either of what you provided already.
You do know (or expect) that this code will throw an exception if there is a null reference:
ComponentException<MyUserManagerException>.FailIfTrue([...]);
However, since there is no contract specifying this, ReSharper has to assume that this is just a normal method call which may return without throwing any exception in any case.
Make this method implement the ReSharper contract, or as a simple workaround (which only affects debug mode, therefore no performance penalty for release mode), just after the FailIfTrue call:
Debug.Assert(user != null);
That will get rid of the warning, and as an added bonus do a runtime check in debug mode to ensure that the condition assumed by you after calling FailIfTrue is indeed met.
This is caused by the Resharper engine. These "possible NullReferenceException" happen because someone (probably at Resharper) has declared/configured somewhere an annotation on the method.
Here is how it works: ReSharper NullReferenceException Analysis and Its Contracts
Unfortunately, sometimes, these useful annotation are just wrong.
When you detect an error, you should report it to JetBrains and they will update the annotations on the next release. They're used to this.
Meanwhile, you can try to fix it by yourself. Read the article for more :)
Please check if you have any user==null if check above the given code. If there is, then ReSharper thinks that the variable "can be null" so recommends you to use a check/assert before referencing it. In some cases, that's the only way ReSharper can guess whether a variable can or cannot be null.

Can C# nameof operator reference instance property without instance?

I regularly want to get the name of an instance property of a type, when I have no instance. Currently to do this, I use the following inhouse function which interprets the Expression[Func[T, object]] parameter and returns the property name:
var str = LinqExtensions.NameOf<ClientService>(x => x.EndDate);
// Now str == "EndDate"
However it seems a shame not to use the built in nameof operator.
Unfortunately it seems that the nameof operator requires either an instance, or, to reference a static properties.
Is there a neat way to use the nameof operator instead of our in house function? For example:
nameof(ClientService.EndDate) // ClientService.EndDate not normally syntactically valid as EndDate is instance member
EDIT
I was completely wrong, the syntax nameof(ClientService.EndDate) as described actually works as is.
In the past, the documentation explicitly explained this, reading in part:
In the examples you see that you can use a type name and access an instance method name. You do not need to have an instance of the type… [emphasis mine]
This has been omitted in the current documentation. However, the examples still make this clear. Code samples such as Console.WriteLine(nameof(List<int>.Count)); // output: Count and Console.WriteLine(nameof(List<int>.Add)); // output: Add show how to use nameof to obtain the string value with the name of an instance member of a class.
I.e. you should be able to write nameof(ClientService.EndDate) and have it work, contrary to your observation in the question that this would be "not normally syntactically valid".
If you are having trouble with the syntax, please provide a good Minimal, Complete, and Verifiable code example that reliably reproduces whatever error you're getting, and provide the exact text of the error message.
Great answer by #Peter Duniho.
In case of name clashes, you can also do the following:
ClientService clientservice;
var str = nameof(clientservice.EndDate);
Not efficient, but curious enough.

Uses for [Obsolete(string, bool)] attribute for .NET

Note: I already checked msdn, it doesn't address my actual question, see below.
I'm trying to use the obsolete attribute on a (obviously obsolete) constructor in one of my classes. Here's the scenario:
I want to be able to force the developer to update to the new constructor without affecting already existing and deployed code. This way I can deploy my code to production just fine, but from a developers perspective, whenever they go into their code, instead of just getting a "warning" which I'm sure they'll just ignore, I want them to get a compile error because the status quo is no longer ok.
So my question is, will this affect only developers, or all calling apps, or do I have the whole thing wrong?
sample code:
public class MyClass
{
private string _userID; //new code
[Obsolete("This constructor is obsolete, please use other constructor.", true)]
public MyClass()
{
_userID = ""; //defaulting to empty string for all those using this constructor
}
public MyClass(string userID)
{
_userID = userID; //this is why they need to use this constructor
}
}
Any and all help will be appreciated, thanks in advance!
Yes, this primarily affects the compiler - any pre-built code won't be affected... unless that code explicitly checks for this attribute. For example, some serialization code (XmlSerializer, IIRC) checks for this - so it might not be entirely side-effect free... but in principal existing code won't usually be affected until they try to compile next.
Of course, if you are using this code from something that uses dynamic compilation (for example ASP.NET without pre-compile) then all bets are off.
The attribute is only an instruction to the compiler. Already existing binaries can still use the constructor.
So my question is, will this affect only developers, or all calling apps, or do I have the whole thing wrong?
This will only be used at compile time, by the compiler. It will not affect applications which have already been deployed.
As such, this will have the behavior you are trying to accomplish.
This is what [Obsolete] already does, no extra help is needed. It is not a compile time warning, it generates an error:
error CS0619: 'ConsoleApplication1.MyClass.MyClass()' is obsolete:
'This constructor is obsolete, please use other constructor.'

Passing a 'Type' to a Generic Constructor

Afternoon, evening... whatever it is where you are ;)
I'm working on a 'ThreadManager' that will execute a set of 'ManagedThread<>'s. A managed thread is a generic wrapper for a 'ManagableThread', which contains most of the essential methods.
The list of 'ManagableThread's to start up, is based on what comes out of a configuration file, and is generated in the ThreadManager.Start method. This list, is meant to be populated with all of the 'ManagedThread's that are to be... managed. Here is the code that I am trying to use to complete this task, and as I'm sure any competent C# developer will quickly realize - I'm not gonna swing it like this.
public void Start() {
foreach (String ThreadName in this.Config.Arguments.Keys) {
Type ThreadType = null;
if ((ThreadType = Type.GetType(ThreadName)) == null) {
continue;
}
else {
ManagedThread<ThreadType> T = new ManagedThread<ThreadType>(
this,
this.GetConfiguration(ThreadType)
);
this.ManagedThreads.Add(T);
continue;
}
}
}
I've taken a few stabs at this to no avail. If anyone has any suggestions I'd appreciate them. I'm no Generics expert, so this is slightly out of my realm of expertise, so please do refrain from making me cry, but feel free to catch me if I'm a fool.
Thanks in advance to anyone who can offer a hand.
Edit: I suppose I should clarify my issue, rather than make you all figure it out... This code will not compile as I cannot pass 'ThreadType' to the generic parameter for my constructor.
That doesn't make sense.
Generics are compile-time types; you can't have a compile-time type that isn't known until runtime.
Instead, you need to use Reflection:
Type gt = typeof(ManagedThread<>).MakeGenericType(ThreadType);
object t = Activator.CreateInstance(gt, this,this.GetConfiguration(ThreadType));
This isn't possible. Generic parameters must be known at compile time. Your type isn't known until runtime.

C# Method overriding with delegates as parameters, compiler is not infering the input types

Can you please help me here, why the compiler does not infer the lambda input parameter right?
Example:
void Test(Action<string> n)
{
}
void Test(Action<int,string> n)
{
}
Ok so when doing this:
obj.Test(x=>{}); // compiler doesn't know x is a string
If I do this:
obj.Test((x,y)=>{}); // that works, compiler know x is a int and y is a string
Looks like I will have to specify the input parameter type (?)
obj.Test((string x) => {}) // <-- Prefer not doing this
So any reasons why the compiler can't get the type right?
Thanks!
Carlos
I just tried to recreate the problem with Visual Studio 2008, and did a screen capture here: http://screencast.com/t/YTAwNmQ4M
I was not able to reproduce the problem. I have seen Visual Studio do things like this in the past, but building always works, and often it is a memory issue. Closing Visual Studio, along with other programs that might be taking a lot of memory, and then starting Visual Studio back up has often helped.
So, basically, my answer is, "did you try turning on off, and then back on again?"
Looking at your screenshot, the problem is quite simple. Your method name Test is the same as the enclosing class, Test. This is not allowed, and in fact, you should receive the compiler error:
'Test': member names cannot be the same as their enclosing type

Categories