How can i make and call a method without any paramaters? - c#

I want to simply call my method like this:
collect.clear;
instead of,
collect.clear();
in other words, I want to make this method
class collect
{
public List<string> list = new List<string>();
public void Clear()
{
list.clear();
}
}
to be called like so
static void Main(string[] args)
{
collect.clear;
}
is this possible or not at all.

I want to simply call my method like this: collect.clear; instead of, collect.clear();
Well, frankly: you don't get to decide what the language syntax is, and in C#, the syntax for invoking a method is: collect.clear();.
Basically, you can't do what you want. You could make it a property, but then you'd need to discard the result (so it can choose between get and set), i.e. with a property get called clear, _ = collect.clear; - frankly I think that's a step back from the (). It is also a terrible idea from the basis of unexpected side-effects; most UI elements (including the debugger) and libraries (serializers, etc) think that they can freely evaluate property gets, so it would be very unexpected it reviewing a property had the side effect of clearing the data! Basically, don't do that.
So; embrace the (). They express the intent here, for your benefit, the benefit of people reviewing/maintaining it, and for the benefit of the compiler.

Related

c# Choosing Between Properties and Methods

After reading this microsoft article about when to use properties and methods, I'm a little bit confused.
At the example at the bottom they say:
The following code example shows a complete application that assumes
that a property access is computationally inexpensive. The
EmployeeData class incorrectly defines a property that returns a copy
of an array.
specifically
The EmployeeData class incorrectly defines a property that returns a
copy of an array.
What would be the right way to do it?
fiddle of the example code
This is just a guideline, but your properties should be as lightweight as possible. Copying an array, just like in the example, is quite expansive for a property. It should be a method. This way, anyone using this code knows it could take a bit of time. Properties usually reflect accessors for private fields, so people expect it to return almost immediately. Hope this makes sense.
The property is "incorrect" because the code inside it is slow.
public EmployeeRecord[] Employees
{
get
{
return CopyEmployeeRecords(); // slow code in property - bad
}
}
Instead, write a method:
public EmployeeRecord[] Employees()
{
return CopyEmployeeRecords(); // slow code in method - ok
}
The section
use a method, rather than a property, in the following situations.
in the article you were reading tells you to use a method instead of a property of the property returns an array.
So the right way to do this would be creating a method to copy the array.

Avoiding repeatedly allocating an Action object without a variable / member

Often I need to minimise object allocations within code that runs very frequently.
Of course I can use normal techniques like object pooling, but sometimes I just want something that's contained locally.
To try and achieve this, I came up with the below:
public static class Reusable<T> where T : new()
{
private static T _Internal;
private static Action<T> _ResetAction;
static Reusable()
{
_Internal = Activator.CreateInstance<T>();
}
public static void SetResetAction(Action<T> resetAction)
{
_ResetAction = resetAction;
}
public static T Get()
{
#if DEBUG
if (_ResetAction == null)
{
throw new InvalidOperationException("You must set the reset action first");
}
#endif
_ResetAction(_Internal);
return _Internal;
}
}
Currently, the usage would be:
// In initialisation function somewhere
Reuseable<List<int>>.SetResetAction((l) => l.Clear());
....
// In loop
var list = Reuseable<List<int>>.Get();
// Do stuff with list
What I'd like to improve, is the fact that the whole thing is not contained in one place (the .SetResetAction is separate to where it's actually used).
I'd like to get the code to something like below:
// In loop
var list = Reuseable<List<int>>.Get((l) => l.Clear());
// Do stuff with list
The problem with this is that i get an object allocation (it creates an Action<T>) every loop.
Is it possible to get the usage I'm after without any object allocations?
Obviously I could create a ReuseableList<T> which would have a built-in Action but I want to allow for other cases where the action could vary.
Are you sure that creates a new Action<T> on each iteration? I suspect it actually doesn't, given that it doesn't capture any variables. I suspect if you look at the IL generated by the C# compiler, it will cache the delegate.
Of course, that's implementation-specific...
EDIT: (I was just leaving before I had time to write any more...)
As Eric points out in the comment, it's not a great idea to rely on this. It's not guaranteed, and it's easy to accidentally break it even when you don't change compiler.
Even the design of this looks worrying (thread safety?) but if you must do it, I'd probably turn it from a static class into a "normal" class which takes the reset method (and possibly the instance) in a constructor. That's a more flexible, readable and testable approach IMO.

Is it bad coding style to not assign a new instance to a variable?

At the top of my program I have a code segment that looks like this
var XXXAssembler = new XXXAssembler(ctx);
XXXAssembler.LoadXXX();
var YYYAssembler = new YYYAssembler(ctx );
YYYAssembler.LoadYYY();
var ZZZAssembler = new ZZZAssembler(ctx);
ZZZAssembler.LoadZZZ();
In the above logic I use each varaible once to call the respective loader, and I don't use the variables anywhere else.
I can change the code to this
new XXXAssembler(ctx).LoadXXX();
new YYYAssembler(ctx ).LoadYYY();
new ZZZAssembler(ctx).LoadZZZ();
This reduces the size of the code, but I'd like to think it simplifies it as well. I could see the usefulness of variables for debugging, but I don't think that's necessarily a good reason. Others may disagree.
Is the non-varaible version considered bad coding style?
Unless you're going to use the object assigned to the Assembler variable, then there's no need for it.
I'd say get rid of it, clean up the code, and then if you need it later you can bring it back.
new XXXAssembler(ctx).LoadXXX(); is absolutely fine as long as you don't have use the reference returned by new XXXAssembler(ctx) elsewhere.
If u ask me, the size of the code doesn't matters. Only matter is that, when you see the code 1 year later, to know how it does what it needs to do, and how to rewrite / reuse / etc.
As you mention, the only technical reason to assign the created object to a variable is if you need to use it or look at it somewhere. If you're confident that you'll never need to do this, you don't need to create a new variable, and you can shorten up your code a bit.
But I'll offer up two caveats:
(1) I often find that I need to look at the output of a method before it returns, or at the instance of the object created by the new statement when I'm debugging. So sometimes instead of doing this:
public MyObject ReturnSomeObject()
{
return new MyObject();
}
I'll do this instead:
public MyObject ReturnSomeObject()
{
var myObject = new MyObject();
return myObject;
}
Just so I can look at it in the debugger. It clutters up my code a bit, but it can be very helpful when I'm trying to figure out why something else went wrong.
(2) If you find that you can do the sort of thing you're describing very often, you may want to take a harder look at how your classes are structured. What's the point of a class that has a method that returns nothing and which doesn't modify the internal state of the class in any fashion that you're interested in? To take your example above, presumably your various LoadXXX() methods should return some sort of status code, or modify some status property of the object, or return a pointer to the file that they loaded, or, well, something. If they do, but you're not bothering to look at it - well, that's another problem. If the methods really don't need to modify any aspect of the object's internal state, then you should look strongly at making them static: it allows you to avoid running the class constructor each time you call them, it expresses their intent more clearly, and it allows the compiler to notify you of a possible inconsistency if you do decide that they need to modify the object state at some point in the future.
Nothing hard-and-fast here, just some guidelines.
If you are never going to use the Object again, but for this case, I don't see the point in giving them names. It adds needless lines of clutter to your code.
I think not assiging to a variable is fine. I do this in many cases, e.g. for some unittest mocks new Mock<IInterfaceToMock>.Object or for callbacks functors SomeFunctionAcceptingCallback(args, new CallbackHandler()).

Are .Net property setters ever called implicitly?

I'm on an ASP.Net 2.0 project, in C#. I have some data that gets stored in session state. For ease of use, it is wrapped in a property, like this:
protected IList<Stuff> RelevantSessionData
{
get
{
return (IList<Stuff>) Session["relevant_key"];
}
set
{
Session["relevant_key"] = value;
}
}
Getting and setting the value works exactly as you'd expect. If I want to clear the value, I just set it to null, and there are no problems. However, in another developer's page, he calls the collection's Clear() method. I thought this would be a bug, but it seems to work, and I don't understand why. It works like so:
Debug.WriteLine(RelevantSessionData.Count); //outputs, say, 3
RelevantSessionData.Clear();
Debug.WriteLine(RelevantSessionData.Count); //outputs 0
Why does this work? My naive expectation would be that the middle line loads the serialized value from session, deserializes into an object, calls Clear() on that object, and then lets the unnamed object fall out of scope. That would be a bug, because the value stored in Session would remain unchanged. But apparently, it's smart enough to instead call the property setter and serialize the newly changed collection back into session.
This makes me a little nervous, because there are places in our legacy code where property setters have side effects, and I don't want those getting called if it's not intended.
Does the property setter always get called in a situation like this? Is something else going on? Or do I completely misunderstand what's happening here?
[Added to explain answer]
It turns out did misunderstand. I knew that objects stored in Session must be serializable, and based on that I made too many assumptions about how the collection behaves internally. I was overthinking.
There is only one instance of the stored object (my IList). Each call to the getter returns a reference to that same instance. So the quoted code above works just as it appears, with no special magic required.
And to answer the title question: No, setters are not called implicitly.
Yes, you are right, this would be a bug if your setter/getters were serializing/deserializing the objects. But this is not the case. Instead you are passing based on reference.
So what's basically happening is that the first line in your example gets the item via the get, and Count is called based on that. Then the seccond line is going out and calling get again, returning the same object, running clear, and then the third line is doing the same as the first.
If you had written your setter/getter something like this, you would have a "bug"
protected IList<Stuff> RelevantSessionData
{
get
{
return (IList<Stuff>) JSON.ConvertFromString(Session["relevant_key"]);
}
set
{
Session["relevant_key"] = JSON.ConvertToString(value);
}
}
In this case, a new object would be created and for each call to the get block. But since your example above is simply passing around the reference to the same object, you're not going to see this "bug".
And I say "bug" since it's not really a bug, it's just more of a misunderstanding of what's happening behind the scenes.
I hope this helps.
Your code is roughly equivalent to:
Debug.WriteLine(((IList<Stuff>) Session["relevant_key"]).Count); //outputs, say, 3
((IList<Stuff>) Session["relevant_key"]).Clear();
Debug.WriteLine(((IList<Stuff>) Session["relevant_key"]).Count); //outputs 0
Even if you only call the getter, you are clearing the collection. So the debug output seems normal.
You can expect property setters to be called if:
The are publicly visible (visible to other assemblies).
They implement the setter as part of an interface visible to other assemblies. In some cases, such as
They are used in WPF binding (but the framework will follow the rules about the BindingMode).
They are used in MEF with the ImportAttribute.
They are used in some other binding framework (you get the idea).
You shouldn't run into problems if, for interfaces defined by others, you meet the pre- and post-conditions of the operation.
Edit: I agree with the above. My first choice for exposing a collection is:
private readonly List<T> _sources = new List<T>();
/* Or ICollection<T>, ReadOnlyCollection<T>, or IList<T>, or
* (only a real option for `internal` types) List<T>
*/
public IEnumerable<T> Sources
{
get
{
return _sources;
}
}
If you absolutely must initialize the list after the object is created, then you can use something like this as the second option:
public IList<T> Sources
{
get;
private set;
}
There are situations where the above practices aren't necessarily the best answer, but these are the two most common (IMO?).

Useful mini patterns (not design patterns)

My most used mini pattern is:
VideoLookup = new ArrayList { new ArrayList { buttonVideo1, "Video01.flv" },
new ArrayList { buttonVideo2, "Video02.flv" },
new ArrayList { buttonVideo3, "Video03.flv" },
new ArrayList { buttonVideo4, "Video04.flv" },
new ArrayList { buttonVideo4, "Video04.flv" }
};
This means that rather than a switch statement with a case for each button I can instead just compare the button that was clicked with each item in the ArrayList. Then when I've found a match I launch the correct file (although the action that's the 2nd part the "lookup" could be a delegate or anything else).
The main benefit is that I don't have the problem of remembering to add all the correct code for each switch statement case, I just add a new item to the lookup ArrayList.
(Yes I know using an ArrayList isn't the best way to go, but it's old code. And I know that looping through an array each time isn't as efficient as using a switch statement, but this code isn't in a tight loop)
Does anyone else have any mini-patterns they use that save time/effort or make code more readable? They don't have to just be GUI related.
Update: Don't copy this code, I knew it was bad, but I didn't realise how bad. Use something like this instead.
Hashtable PlayerLookup = new Hashtable();
PlayerLookup.Add(buttonVideo1, "Video01.flv");
PlayerLookup.Add(buttonVideo2, "Video02.flv");
PlayerLookup.Add(buttonVideo3, "Video03.flv");
PlayerLookup.Add(buttonVideo4, "Video04.flv");
string fileName = PlayerLookup[currentButton].ToString();
please please please omg use this version.
VideoLookup = new Dictionary<Button, string> {
{ buttonVideo1, "Video01.flv" },
{ buttonVideo2, "Video02.flv" },
{ buttonVideo3, "Video03.flv" },
{ buttonVideo4, "Video04.flv" },
{ buttonVideo4, "Video04.flv" }
};
You could just create a struct or object that has a button reference and a string representing the file name and then a List of these things. Or, you could just use a Dictionary and make it even easier on yourself. Lots of ways to improve. :)
On the subject of switches, I write this kind of thing a lot:
public Object createSomething(String param)
{
return s == null ? new NullObject() :
s.equals("foo") ? new Foo() :
s.equals("bar") ? new Bar() :
s.equals("baz") || s.equals("car") ? new BazCar() :
new Object();
}
I think it looks more readable compared to regular switch statements and has the ability to have more complex comparisons. Yeah, it'll be slower because you need to compare each condition but 99% of the time that doesn't matter.
In Java, I sometimes find that private inner classes which implement a public interface can be very helpful for objects composed of tightly-coupled elements. I've seen this mini-pattern (idiom) discussed in the context of creating UIs with Allen Holub's Visual Proxy architecture, but not much beyond that. As far as I know it doesn't have a name.
For example, let's say you have a Collection interface that can provide an Iterator:
public interface Collection
{
...
public Iterator iterate();
}
public interface Iterator
{
public boolean hasNext();
public Object next();
}
If you have a Stack that implements Collection, then you could implement its Iterator as a private inner class:
public class Stack implements Collection
{
...
public Iterator iterate()
{
return new IteratorImpl();
}
private class IteratorImpl implements Iterator
{
public boolean hasNext() { ... }
public Object next() { ... }
}
}
Stack.IteratorImpl has complete access to all of Stack's private methods and fields. At the same time, Stack.IteratorImpl is invisible to all except Stack.
A Stack and its Iterator will tend to be tightly coupled. Worst case, implementing Stack's Iterator as a public class might force you to break Stack's encapsulation. The private inner class lets you avoid this. Either way, you avoid polluting the class hierarchy with something that's really an implementation detail.
In my last job I wrote a C# version of the Enforcements concept introduced in C++ by Andrei Alexandrescu and Petru Marginean (original article here).
This is really cool because it lets you interweave error handling or condition checking in with normal code without breaking the flow - e.g.:
string text = Enforce.NotNull( myObj.SomeMethodThatGetsAString(), "method returned NULL" );
This would check if the first argument is null, throw an EnforcementException with the second argument as the message if it is, or return the first argument otherwise. There are overloads that take string formatting params too, as well as overloads that let you specify a different exception type.
You could argue that this sort of thing is less relevant in C# because the runtime checking is better and already quite informative - but this idiom lets you check closer to the source and provide more information, while remaining expressive.
I use the same system for Pre and Post condition checking.
I might write an Open Source version and link it from here.
for when I'm churning out code fast (deadlines! deadlines! why am I on stackoverflow.com? deadlines!), I wind up with this kind code:
Button1.Click += (o,e) => { DoSomething(foo); };
Will this cause me memory leaks at some point? I'm not sure! This probably deserves a question. Ack! Deadlines!
For Windows forms I'll often use the Tag field to put a psuedo-command string so that I can have a single event handler for a shared set of buttons. This works especially well for buttons that do pretty much the same thing but are parameterized.
In your first example, I would set the Tag for the buttons equal to the name of the video file -- no lookup required.
For applications that have some form of text-based command processor for dispatching actions, the Tag is a string that is just fed into the command processor. Works nice.
(BTW: I've seen the term "idiom" used for mini-patterns...)
A new idiom that I'm beginning to see in C# is the use of closure parameters that encapsulate some configuration or setup that the method will need to function. This way, you can control the relative order that code must run from within your method.
This is called a nested closure by Martin Fowler: http://www.martinfowler.com/dslwip/NestedClosure.html
Perhaps there's already a better way of doing this (vbEx2005/.Net2.0), but I've found it useful to have a class of generic delegate-creators which accept a method that takes some parameters, along with the values of either all, or all but one, of those parameters, and yields a delegate which, when invoked, will call the specified function with the indicated parameters. Unlike ParamArray-based things like ParameterizedThreadStart, everything is type-safe.
For example, if I say:
Sub Foo(param1 As Integer, param2 As String)
...
End Sub
...
Dim theAct as Action(of Integer) = _
ActionOf(of Integer).NewInv(AddressOf Foo,"Hello there")
theAct(5)
...
the result will be to call Foo(5, "Hello there") on object where Foo was declared. Unfortunately, I end up having to have separate generic classes and methods for every different number of parameters I want to support, but it's nicer to have all the cut-and-paste in one file than to have extra code scattered about everywhere to create the appropriate delegates.

Categories

Resources