In C++ I can declare a fully functional anonymous class inside a piece of code where it's needed so that I don't have to declare it if I need it only once.
The code should be like this
Class MyClass
{
Class
{
String string1;
String string2;
void MyMethod();
} Strings;
}
And call it the members with MyClass.Strings.string1, MyClass.Strings.MyMethod() and so on. This way I can elegantly group my code.
Is there a way to do the same thing in C#?
This way I can elegantly group my code.
I don't how can this help you to elegantly group your code, but there is no such thing in C#. There are anonymous classes but they only work in local scopes:
// inside a method:
var obj = new { String1 = "Hello", String2 = "World" };
And you can't add methods to them.
The closest thing you can get to is an inner class/struct:
class MyClass
{
class MyStrings
{
String string1;
String string2;
void MyMethod() { ... }
}
MyStrings Strings;
}
I agree Sweeper. This functionality adds just cluttering code. You should consider to make your code as easy as possible to understand. This means if you feal that you want to group your code, giving every group it´s own functionality, why not make this group a class and give it a name that directly reflects what its purpose is.
What you can do is use an anonymous class which in C# doesn´t implement any interface but just derives from object:
var a = new { MyMember = 1, MyFunc = new Func<int>(() => 1) };
now you can invoke both members of this type:
Console.WriteLine(a.MyMember);
var retVal = a.myFunc();
But does this make your code any better in a way that it´s easier to understand what it does? I doubt so. Give your instances - even when used only once - a name that describes what their intention - the idea behind - is. Don´t make it hard for others to understand your code by cryptifying it.
Apart from this you can restrict the use of your class to be private by nesting it within another one:
public class MyClass
{
private class Strings { /* ... */ }
}
Now your class is just visible to itself and within MyClass (and in other classes that are nested in MyClass of course). This makes it impossible to access the class from the outside like so:
var strings = new MyClass.Strings();
Try making the inner class static. That way you will be able to use the syntax you describe:
class MyClass {
public static Strings {
public static string string1;
public static string string2;
public static void MyMethod() {}
}
}
You can then call: MyClass.Strings.string1 = "Hell, world!";
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I sometimes need to go online and find a tutorial for something. I am often finding that some people put code like this:
this.button1.Text = "Random Text";
Then I find code that is just like this:
button1.Text = "Random Text";
Is it better to use the this.whatever or does it not matter?
It depends. Here's an example class:
class A
{
private int count;
public A(int count)
{
this.count = count;
}
}
In this case, the "this." is mandatory because it disambiguates the reference on the left of the assignment. Without it, it is not clear to you reading the code whether "count" would refer to the parameter or the field. (It is clear to the compiler, which has rules to follow.) But in most cases, it is purely a matter of preference.
Write all your code to emphasize salient points to the reader. If you feel that it is important for the reader to clearly understand that an identifier refers to an instance member then use this. If you feel that its an unimportant and distracting implementation detail, don't. Use good judgment to make your code readable.
this is just to make it clear, in some cases we have to use this:
Differentiate between parameter and local member:
//local member
object item;
private void SomeMethod(object item){
this.item = item;//must use this
}
Pass the current class instance into another method:
public class SomeClass {
private void SomeMethod(SomeClass obj){
//....
}
private void AnotherMethod(){
SomeMethod(this);//pass the current instance into SomeMethod
//.....
}
}
Use in extension methods:
public static class SomeClassExtension {
public static void SomeClassMethod(this SomeClass obj){
//use obj as a reference to the object calling this method...
}
}
Call a constructor from another constructor (with different signature):
public Form1(string s) : this() {//Call the Form1() before executing other code in Form1(string s)
//......
}
Use for declaring indexers:
public class SomeClass {
//declare an index returning a string
public string this[int index] {
get {return ...}
set { ... }
}
}
Use auto-properties in struct:
public struct SomeStruct {
public object AutoProp1 {get;set;}
public object AutoProp2 {get;set;}
public SomeStruct() : this() //must use this
{
AutoProp1 = someObject;
AutoProp2 = someObject;
}
}
Cast the current instance to the based classes/types:
public class ClassB : ClassC {
//...
}
public class ClassA : ClassB {
public ClassA(){
((ClassC)this).MemberOfClassC ... ;//There might be some member in ClassC
//which is overridden in ClassA or ClassB, casting to ClassC can help we invoke the original member instead of the overridden one.
}
}
There might be some other uses of this, however I'll update later if I think out.
It does not matter, it is a matter of style. I tend to omit this, since it is just extra code to mentally parse.
The only case it matters is when there is a naming conflict between local and instance variables, in which case this can be used to disambiguate between a field and a local variable.
Here is an example of the type of situation where it does matter:
public class Foo
{
private string x;
public Foo(string x)
{
// x = x; Assigns local parameter x to x, not what we want
this.x = x; // Assigns instance variable x to local parameter x: this disambiguates between the two.
}
}
an example of using this can be to access class variable when you already have a similar variable in the scope. Otherwise it is mostly of choice.
Example
public class Test
{
public string firstName { get; set; }
public void temp(string firstName)
{
firstName = this.firstName;
}
}
In regards to fields the only case where this is explicitly needed is when there is a naming conflict:
public class Foo
{
private string bar;
public Foo(string bar)
{
this.bar = bar;
}
}
So some will prepend an underscore:
public class Foo
{
private string _bar;
public Foo(string bar)
{
_bar = bar;
}
}
Usually it will not matter. This reason why you might use this. is to explicit say that you want to reference a property/field that belong to the current class.
Again, there are not many occasions when you are likely to need this, but for example you might have a local variable with the same name as a class level property/field. Then you could use this..
For example:
class MyClass
{
string s = "1";
void MyFunction(string s)
{
//s = local value as passed in to function
//this.s = "1"
}
}
It doesn't usually matter. The this keyword "refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method."
Check out this article.
http://msdn.microsoft.com/en-us/library/dk1507sz.aspx
generally it doesn't matter, but if you pass in a variable called, say button1, to a class method that already has a member called button1, then you'll need to disambiguate which one you really meant.
This is probably why people now use this. to explicitly say which variable you meant, if you use this practice all the time, you'll not get it wrong in the few cases where its important.
Of course, you could ensure that all member variables are uniquely named, say with a prefix like m_, but that's fallen out of fashion nowadays, people prefer to write out this.
It really depends on the situation.
http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.80).aspx
To qualify members hidden by similar names
To pass an object as a parameter to other methods
To declare indexers
As others have already pointed out, it is useful in distinguishing field/property with method variables, One other place where this is required is to invoke Extension methods on current instance. For example this.ExtensionMethod(); would work, but not just ExtensionMethod();
Other than that, its a matter of personal choice, some call it redundant and some like to use it. It totally depends on you and your team.
Personally I like to use this with class members, specially for Forms method if working on code-behind of winform, like this.Close();
For more discussion when to use this see: When do you use the "this" keyword?
I have around 300 functions and don't want to have to make a wrapper for each of them.
class B
{
func(vartype somevar, int otherparam)
{
//code
}
}
Then I want to do this
class A:B(vartype somevar)
{
Asfunc2()
{
this->func(1); //basically somevar would already be filled in when called and it'd just need the 1 param.
}
}
You could call base constructor as follows:
public class Manager : Employee
{
public Manager(int annualSalary)
: base(annualSalary)
{
//Add further instructions here.
}
}
The reference is here.
What you described is looks like binding function parameters in JavaScript but it's not possible in C# as far as I know.
I was thinking about the situation you described and was using the following linqpad script to go over what this would imply:
void Main()
{
B b = new B();
b.CallA().Dump();
}
class A
{
public string CallA(string someVar)
{
return string.Format("{0} says Hello", someVar);
}
}
class B : A
{
public string CallA(string someVar = null)
{
return base.CallA(someVar);
}
}
You essentially end up with an overloaded CallA method. This can will get sticky. What about the following code that you would execute in the Main method after creating an instance of B:
((A)b).CallA(); //You actually want to call A.CallA
This still calls b.CallA().
Just be careful. This does not feel like a good design.
If you have access to class B, then I believe the only way to do what you want is to make somevar a global variable, which will be initialized in the constructor.
You might be able to get around this with reflection, but it seems more likely you have a code smell, and the real problem is in the design, not the implementation.
I am converting some java code C# for use in my MonoDroid application. I have some snippets where interfaces are declared and then initialized in to objects. I am not 100% sure on the best approach to implement these in to C#.
For example:
public class NumberPicker {
public interface Formatter {
String toString(int value);
}
public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER =
new NumberPicker.Formatter() {
//some code here
};
}
What would be the equivalent or best approach to do this in c#?
for simple "single-use" interfaces with one function (like event listeners, for example), you could think of rewriting the code to use delegates and anonymous functions instead.
delegate String Formatter(int n);
...
Formatter TWO_DIGIT_FORMATTER = delegate(int n) {
//code here
};
you can then use TWO_DIGIT_FORMATTER like a function ( TWO_DIGIT_FORMATTER(12) ).
Anonymous classes (which is what's happening in your java code) don't exist in C#, but delegates suffice in cases like this.
You would have to create a class that implements the Formatter interface and then create an instance of that.
i.e.
public class MyFormatter : IFormatter
{
public string ToString(int value)
{
//implementation
}
}
Then create an instance of MyFormatter with the new operator.
public static IFormatter TWO_DIGIT_FORMATTER = new MyFormatter ();
The 'I' prefix for interfaces is something done in the .net world but it isn't required, just convention.
So the easiest way I have found to handle this situation is to create a private nested class within your main class and then have it inherit from as many interfaces as you need. Such as IOnClickListener, IOnMouseDownListener, and then declare it at the top of your class and reuse it over and over wherever needed. Makes it much easier... If you have interfaces that repeat or have the same method names you can declare them explicitly, for example
IOnClickListener.OnClick(object sender, EventArgs)
{
}
Just as an example, you would obviously want to use the real method names and interface names. Also don't forget to dispose of the instance in your OnDestroy.
Updated to reflect to my own source
I'm in process of building my first winform application in c# and I'm trying to figure out the best practice for structuring my classes to work smoothly when I use them in my forms.
I have a couple of examples which I will try to explain the best way i can.
When working with get/set variables in a class, the best practice should be something like this:
JobMove.cs
public class JobMove
{
private List<string> jobNames { get; set; }
public string Scanner;
public JobMove()
{
this.Scanner = Properties.Settings.Default.Scanner;
}
public void ListSelected(ListBox lbx)
{
foreach (string jName in this.jobNames)
{
lbx.Items.Add(jName);
}
}
public static List<string> GetCheckedJobs(ListView lw)
{
int countChecked = lw.CheckedItems.Count;
int itemCount = 0;
List<string> jList = new List<string>();
foreach (ListViewItem item in lw.CheckedItems)
{
JobInfo jobInfo = Job.Find(Convert.ToInt32(lw.Items[item.Index].SubItems[1].Text));
jList.Add(jobInfo.Name);
itemCount++;
}
return jList;
}
}
My problem is when I combine this with my forms and I call this, then I would try to do something like this:
MyForm1.cs
public partial class MyForm1 : Form
{
private void btnMoveJobs_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Scanner = cbxScanners.SelectedItem.ToString();
JobMove moveJobs = new JobMove();
frmMoveJobs FrmMoveJobs = new frmMoveJobs();
FrmMoveJobs.ShowDialog();
}
}
MyForm2.cs
public partial class frmMoveJobs : Form
{
public frmMoveJobs()
{
InitializeComponent();
JobMove moveJobs = new JobMove();
lblFrom.Text = moveJobs.Scanner;
moveJobs.ListSelected(lbxJobsToMove);
cbxMjScanners.DataSource = System.Enum.GetValues(typeof(Scanners));
}
}
But when I call MyClass in MyForm2 and I want to call the DoSomethingElse method, then myString will be reset to a null value. And that makes sense to me, but how do I work around this?
I tried to figure out what to use here to get easier around these flaws in my code, but my knowledge is far too weak to just implement an easy solution.
I know I could just store this variable in Settings.settings as an example, but to me that just seems like a real overload for such a simple task.
I might just need a point in the right direction to right on what to do in this situation.
If you do a MyClass myClass = new MyClass(); then indeed - the values are independent and unrelated. If you want to share the MyClass instance then pass the MyClass instance between the forms. Perhaps:
using(var form2 = new Form2()) {
form2.SensibleName = existingMyClassInstance;
form2.ShowDialog();
}
(note the using above btw; when using ShowDialog() it is your job to make sure the form is disposed; it only gets disposed automatically if using Show())
Firstly, they're properties, not variables (the variables are the underlying data source).
Secondly, the whole point of get/set accessors is so you can get and set the value without needing helper methods.
Thirdly, and as to your problem, you're creating a new instance of the class in each form (hinted at by the new keyword) and the value of the property will be whatever it is initialised as on construction of the instance (or not.) i.e. the values of properties are not shared between different instances of the same type.
Think of the mold for a key: I can get multiple instances of the key cut from a "blueprint", but any damage that one suffers won't be reflected by the rest - they're unique in that sense.
If you want the forms to both access the same instance of that type, then you will need to stash the instance somewhere in your code which is accessible to both.
A few options:
Pass in an instance of MyClass in the form2's constructor.
Make MyClass a static property of either Form1 or Form2 and access it via that on the other form.
Make MyClass static (not recommended).
If you want to use the instance of MyClass created in MyForm1 inside of MyForm2, you need to provide it to MyForm2.
Something like this would work:
public partial class MyForm2 : Form
{
public MyForm2(MyClass given)
{
InitializeComponent();
given.DoSomethingElse();
}
}
Easy Solution:
private static string myString { get; set; }
Why: because you initialize the class again when initializing Form2 and it will create a new class. With the "static" keyword you create a property which is the same in all instances of this class.
BUT: please read some books before continuing, this would be the solution to this problem, but the source of many others. Try to understand C# and Forms first, than (or alongside with reading/learning) start coding!
this is because each of your form has a new object of "MyClass".
To achieve what you want to do use a static property... this won't be initialized and gives back the same value for each object of MyClass
it looks like this
public class MyClass {
public static string myString { get; set; }
public void ChangeMyString(string newString)
{
myString = newString;
}
public void DoSomethingElse()
{
MessageBox.Show(myString);
}
}
I am reading Josh Bloch's book Effective Java and he suggests using a builder design pattern when building objects that have large amounts of members. From what I can see it isn't the vanilla design pattern but looks like his variation. I rather like the look of it and was trying to use it in a C# web application that I am writting. This is the code written in Java and works perfectly
public class Property {
private String title;
private String area;
private int sleeps = 0;
public static void main(String[] args) {
Property newProperty = new Property.Builder("Test Property").Area("Test Area").Sleeps(7).build();
}
private Property(Builder builder) {
this.title = builder.title;
this.area = builder.area;
this.sleeps =builder.sleeps;
}
public static class Builder{
private String title;
private String area;
private int sleeps = 0;
public Builder (String title){
this.title = title;
}
public Builder Area(String area){
this.area = area;
return this;
}
public Builder Sleeps(int sleeps){
this.sleeps = sleeps;
return this;
}
public Property build() {
return new Property(this);
}
}
}
When I put this into what I think is the C# equivalent
public class Property
{
private String title;
private String area;
private Property(Builder Builder)
{
title = Builder.title;
area = Builder.area;
}
public static class Builder
{
// Required parameters
private String title;
private String area;
// Optional parameters
private int sleeps = 0;
public Builder(String val)
{
this.title = val;
}
public Builder Area(String val)
{
this.area = val;
return this;
}
public Builder Sleeps(int val)
{
this.sleeps = val;
return this;
}
public Property build()
{
return new Property(this);
}
}
}
Then I get compiler warnings. Most of them "cannot declare instance members in a static class".
So my question is firstly what have I missed? If I have missed something, can I do it in the manner Josh Bloch recommends but in C#, and lastly, and this one important too, is this thread-safe?
public static class in Java means that you define a static nested class. That means that it is logically contained in another class but instances of it can exist without a reference to it's outer class. A non-static nested class is called an "inner class" and instances of it can only ever exist in relation to an instance of the outer class.
In C# a static class is one that can't be instantiated and thus can't have any non-static members. There is no direct language-level equivalent to this construct in Java, but you can easily prevent instantiation of a Java class by providing only a private constructor.
Short Java recap:
All Classes defined inside another Class are "nested Classes"
nested Classes that are not static are called inner Classes
instances of inner Classes can only exist in relation to an instance of the outer Class
static nested Classes have no separate name
static nested Classes are largely independent from their outer class (except for some privileged access).
I'd be happy if some C# guru told us how inner/nested classes are handled in C#/.NET.
I think you can achieve pretty much the same effect if you create Builder as a top level class ( for that's exactly what it is in Java ) and create a factory method to receive the builder in order to keep the constructor private ( which in turn would let you return subclasses instances if needed).
The point is to let the builder perform the steps needed to create the object.
So ( without knowing much about C# you could try something like this )
// My naive C# attempt:P
public class Property
{
public static void main( String []args )
{
Property p = Property.buildFrom( new Builder("title").Area("area").Etc() )
}
public static Property buildFrom( Builder builder )
{
return new Propert( builder );
}
private Property ( Builder builder )
{
this.area = builder.area;
this.title = builder.title;
// etc.
}
}
public class Builder
{
public Builder ( String t )
{
this.title = t;
}
public Builder Area( String area )
{
this.area = area;
return this;
}
// etc.
}
The whole point of having Builder as an static inner class of property is to create a high coupling among the two ( as if they where one ). That's why build method in Builder calls the private "Property" constructor.
Probably in C# you could use an alternate artifact to create the same coupling.
saua has the right answer, but I would like to be clear about your example in particular:
In the C# version, you should remove the static keyword from the inner class. It doesn't mean the same thing as the Java version, and indeed the effect it has in the Java version is the normal behaviour for inner classes in C#.
In Java a nested class is by default associated with a particular instance of its containing class. An instance of the nested class can access variables and methods of the containing instance. If the nested class has the "static" keyword then it is not associated with an instance of the outer class. It is in this sense that Bloch uses the "static" keyword on the Builder class.
"Static" means something different when applied to a nested class in C#. I don't know what keyword you would use in C#, or even if it is necessary. Did you try leaving the static keyword out of the class definitions?
Use of "static" in Java class definitions is discussed in Item 18 of Effective Java.
I'm not sure what Java is doing with the static class declaration, but in C#, a static class is one that only has class-level members and, by definition, can not be implemented into an instance. It's like the old VB difference between Class and Module.
I don't know why C# is complaining, but I can say that the code is thread-safe. If you were creating two or more instances of Property at the same time, each in their own threads, you wouldn't run into any problems.
I will try removing the static keyword. My other thought was, as others have already suggested, was to create the builder class as a top level class.
To answer several comments about how to get Java's inner class behavior in C#, it would seem that the reference to the enclosing class needs to be passed in the constructor of the inner class (from a quick Google - C# may have since added the capability).
public class Outer
{
...
void SomeMethod() {
Inner workerBee=new Inner(this);
}
...
class Inner
private Outer outer;
{
Inner(Outer out) {
outer=out;
}
}
}
So C# just makes explicit what Java did implicitly, including explicitly needing the reference to access members of the outer class.
Personally, I have never liked the Java implicit accesses to the outer classes members, since it seems too easy to trip up and accidently break encapsulation - I nearly always create my inner classes as static and pass them a reference to the outer class.
Assuming that your class has publicly settable properties corresponding to the builder members, you don't need Bloch's builder pattern in C#. You can use Object Initializers:
public class Property
{
public String Title {get; set};
public String Area {get; set};
public int Sleeps {get; set};
public static void main(String[] args)
{
Property newProperty = new Property {Title="Test Property", Area="Test Area", Sleeps=7};
}
}
This won't be possible if you need more encapsulation.