Not able to specify the public variable class - c#

I have a problem with the var keyword
I have defined it like this at the form load
public partial class form1 :form
{
public var a;
private void form1_load(object sender, eventargs e)
{
// i have used "a" like this....
a = abc.members blahhhh blahhhhh
bindingsource1.datasource = a;
datagridview1.datasource = bindingsource1;
}
}
but I got the error on this line
public Var a;
the type or namespace name 'var' could not be defined
Can I define public class varaible so that I can access this all methods in that class?

var in C# is different from var in other languages; in C# you use var to have the compiler determine the type of a certain local variable for you, but you cannot use it to declare fields/properties.
You have to specify the actual type instead. I have no idea what a is, so I can't tell you what type to use.

You have to use the concrete type instead of var - for example "string", "int", ...
This is because "var" is only syntactic suggar. The compliler interferes the concrete type and insert it instead of var. In your case this is impossible, because the compiler won't look so far as the form_load - it just looks at the expression after the "="
As a side note: you should not define fields as public. Make them private and define public accessors or public propertys for them. In this way you don't leak internal implementation details to the outside world and got no problems if you want to change this implementation-details later on.

If you want to make it a public (and not a local) variable you have to declare it as a specific type, for example 'string', 'int' or a selfwritten class

variables having an implicit type var must be declared at method scope.

public int a; would suffice, i suppose.
As per,
http://msdn.microsoft.com/en-us/library/bb383973.aspx
Only variables that are declared at method scope can have an implicit type var
As you need this for a linq query, you can assign the explicitly typed public variables wherever (inside a function) you run the query. For example,
func()
{
var results = from p1 in phones where p1.name="abc";
MyPublicVariable = results;
}
Where MyPublicVariable could be an enumerable.

Related

Why is the parameter is not updated?

I have a class that uses another class.
The first class have this method:
public void myMethod()
{
//Parameters are an enumeration.
// Really is a exchange variable between this class
//and the other class.
Paramters myParameter = Parameters.Option1;
MyClass2 myOtherClass = new MyClass2(myParameter);
}
The second class:
public enum Parameters { Option1, Option2, Option3 }
MyClass2
{
Parameters _myParameters;
Public MyClass2(Parameters paramParameters)
{
_myParameters = paramParameters;
}
private void clickButton()
{
_myParameters = Parameters.Option2;
this.Dispose();
}
}
What I what it is create a dialog and Parameters are an enumeration that is to serve as exchange between the main window and the dialog to notify about the selection in the dialog.
However, when in the clickButton I change the value of the _myParameters, it is not changed in the object that was passed as parameter in the constructor of MyClass2.
If instead of using an enumeration as exchange variable I create a class that has the enumeration, then I can get the selection. The exchange class would be like this:
class MyExchangeClass
{
Parameters myOption;
}
Then the code would be:
public void myMethod()
{
//Parameters are an enumeration.
// Really is a exchange variable between this class
//and the other class.
MyExchangeClass mySelection= new MyExchangeClass();
MyClass2 myOtherClass = new MyClass2(mySelection);
}
The second class:
public MyExchangeClass
{
Parameters enum MySelection { Option1, Option2, Option3 }
}
class MyClass2
{
MyExchangeClass _mySelection;
Public MyClass2(MyExchangeClassparamParameters)
{
_mySelection= paramParameters;
}
private void clickButton()
{
_mySelection.MySelection = Parameters.Option2;
this.Dispose();
}
}
In this way, the Class1, the main window, gets the updated value in the property of the class MyExchangeClass.
I would like to know why in the first solution the enumeration is not updated, because if it would possible, I would like to avoid the needed to wrap the enumeration in a class.
However, when in the clickButton I change the value of the _myParameters, is not changed in the object that was passed as parameter in the constructor of MyClass2.
No, it wouldn't be. The value was passed in by value - the two variables (myParameter and _myParameters) are independent variables. A change to one variable does not affect the other variable. This is how all types work in C#.
For changes to a parameter within a method to be seen by the caller, you could use a ref parameter, but that's not viable in your case as you're changing an instance variable which was originally populated via a parameter.
You could wrap the value in a mutable class, pass a reference to an instance of that class into MyClass2, and then mutate the object within MyClass2 - that change would be seen within your first class, because that would be changing the data within the object rather than the instance variable of MyClass2. It's hard to know whether or not that's actually a good solution though, as we have so little context - with names like MyClass and myMethod we have no clue as to the bigger picture of what this is trying to achieve.
In your first solution the value of the enumeration inside the class didn't change because enumeration is a value type, and this line:
_myParameters = paramParameters;
made a copy of paramParameters and _myParameters is a completely separate, standalone object.
In your second example, MyExchangeClass is a reference type, so this line:
_mySelection= paramParameters;
made _mySelection point to exactly the same object as paramParameters reference was referring to.
From the documentation:
Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.
And an enumeration is a value type, ibidem:
The value types consist of two main categories:
Structs
Enumerations

What does this code do in c# and what is it's purpose?

public class A {
public Par mParams;
public Par Parameters {
get { return mParams; }
set { mParams = value; }
}
}
I am new to c#
What is public Par Parameters? This seems neither a class or a function. Confused here.
Think of it like a public Par getParameters() and public void setX(Par p) method in Java. So, it is closest to a "function" but it is actually called Property. You can use it like this:
A myObject = new A();
a.Parameters = new Par(...);
This is a property which is backed by a public field, in this case, it is somewhat redundant, mParms should be declared as protected or private.
I recommend that you review this MSDN Programming Guide on Properties. It explains quite well, how they work and what they're used for.
The block of code from Public Par Parameters is a Property
I suspect the line public Par mParams; should actually be private. Its meant to be the underlying variable storing the value of the property.
Its worth pointing out that you do not explicitly need mParams any more in C#. You can define an automatic property, where the compiler creates its own underlying private variable using:
Public Par Parameters { get; set; }
public Par Parameters is a property, used to set or get the value of mParams.
Parameters is a Property of type Par. It has an access modifier (public), which means it is accessible from anywhere in your code.
Your example is a little redundant, because the mParams field is actually publicly accessible, and the property that exposes it doesn't do anything apart from returning and setting the field. However, you could potentially add extra code in each of the "accessors" (the get and set bits). For example to do validation, notify something that a property has been changed, etc.
You use properties in much the same way as fields:
A foo = new A();
// Calls the "get" accessor of the Parameters property
if (foo.Parameters == null)
{
// Calls the "set" accessor of the Parameters property
foo.Parameters = new Par();
}
It is considered a best practice to not allow direct access to member fields (variables) from outside a class. In a typical scenario, the field should therefore be private (or sometimes protected):
private Par mParams;
public Par Parameters
{
get { return mParams; }
set { mParams = value; }
}
There are a few slightly different syntaxes you will want to learn about as well. First, there is the auto-implemented property:
public Par Parameters
{
get;
set;
}
For auto-implemented properties, the C# compiler generates a backing field for you automatically. This saves you from writing some code if our property getter and setter don't need to contain any logic.
You can also use properties to restrict access in ways you cannot achieve with fields:
public Par Parameters
{
get;
private set;
}
Notice the set "accessor" has it's own access modifier. The result is a property that is publicly readable, but only the class itself is allowed to set it. This is similar to:
private Par mParams;
public Par Parameters
{
get { return mParams; }
}
Which does effectively the same thing, but without an auto-implemented property.
In languages that do not support properties, all this would be achieved by creating two methods: GetParameters and SetParameters. In fact, the C# compiler generates some very similarly named methods in the background.
It's shorthand for accessors and mutators. In another example:
private int i = 0;
public int myNumber {
get { return i; }
set { i = value; }
}
Allows you to change the variable i. Like so in code:
className.myNumber = 20;
// className.i is now 20
It's a property, which works very much like a pair of methods (functions) whose only purpose is to give you access to the mParams field. As a bit of syntactic sugar, C# gives you the ability to assign and read to it much as you would a variable. Think of it as two methods, getParameters and setParameters, which you can't call directly, but which are invoked when you access Parameters.
Parameters = new Par(); //Works as though you had run: setParameters(new Par());
Par x = Parameters; //Works as though you had run: Par x = getParameters();
This allows you to use the shorter, more convenient and expressive variable-like syntax, but what you're actually doing is running two "invisible" methods created by the compiler.

Implementing a specific case of a generic, versus deriving from it

I am trying to write out a specific case of a generic class with additional functionality, but I am not sure why the following happens.
Suppose I have a generic class:
class Generic<T>
{
protected T value;
}
If I write out a specific implementation, I can't actually use the specific type I've narrowed it down to:
EDIT: I goofed up, this doesn't work.
class Generic<float>
{
// This doesn't work
public void Add()
{
value + 1.0f;
}
}
But if I inherit from the specific version, it does work:
class Specific : Generic<float>
{
// This does work
public void Add()
{
value + 1.0f;
}
}
In case someone is still reading this, I wanted to point out that this seems to be possible with extension methods:
class Generic<T>
{
public T value;
}
static class Extension
{
public static void Add (this Generic<float> generic)
{
generic.value += 1.0f;
}
}
The downside seems to be that 'value' has to be public or internal.
Your first attempt simply isn't a valid declaration - the part that specifies a class can't specify any type arguments.
If you think about it, how would the CLR know whether or not there was a specialized type available? What would it do if there were two different specializations of the same generic type in two loaded assemblies? It would have to check all the referenced assemblies any time a particular type argument combination was used for the first time. (This couldn't be done at compile-time, as other classes may just be referring to Generic<T>.)
In many cases you can use values of the type in ways which are meaningful to the type using constraints. For example, if you constrain T with where T : IComparable<T> then you can compare any two T values using Compare. Unfortunately there's no way of representing arithmetic operators in this way, although you may want to look at Marc Gravell's generic operator work in MiscUtil.
While I feel your pain, there's simply nothing like this in .NET generics - you'll want to think of alternative designs for whatever problem you're really trying to solve.
in this case :
class Generic<float>
{
// This doesn't work
public void Add()
{
value + 1.0f;
}
}
It doesn't mean that you are working with a Generic class using float as its generic type but it means that the name of the generic type is "float" in the source (instead of using T you are using "float" as its name ) Thus there's no conversion to float.In other words you are using a generic notation as a template that can be substituted with real types later (but not in the template itself and that's why in C++ they are called templates)
In this code :
class Specific : Generic<float>
{
// This does work
public void Add()
{
value + 1.0f;
}
}
you are telling the compiler that you want the specific class be a child of a generic class while it's template type will be replaced by type float.
Generic types are used for arithmetic reusability. That is, you must write something common between all possible Ts in your code.
class Generic<T>
{
protected T value; //it's valid to declare a member whose type is T
public void Add()
{
value + 1.0f; //invalid, because not all T are allowed to add
//with 0.1f by default
//consider T is the type Person
}
public void Print()
{
Type t = typeof(T); //valid, for all T we can get its type
}
}
And when you specified some T (e.g. float in your question), the compiler knows the T is float, so it's valid to add 0.1f to it.
I also looked for similar solution, I think you also got this thinking from ADA or such programming language.
But, as others wrote, making type specific class definition is not generic programming, it's specialization, so the simpliest (and only in C#) way is to create a specified class, based on generic structure:
class Generic<T>
{
protected T value;
public Generic(T val)
{
value = val;
}
}
class Generic_float : Generic<float>
{
public Generic_float(float val)
: base(val)
{
}
public void Add()
{
value = value + 1.0f;
}
}
As you can see, we created a class for the specified case, having the extra ability of extending the structure with fields and methods. This advantage is very good to refine behavior of our objects, and gives ability of implicit cast of the typed generic class to our customized one (with the notice that casting back is not possible):
public void Test()
{
Generic<float> var1 = new Generic<float>(1.5f);
Generic_float var2 = new Generic_float(2.5f);
var1 = var2; // Works, var links to var2's memory field casted as Generic<float>
var2 = var1; // cannot implicitly convert error, if want to use then have to make explicit conversion
}
Don't know if the way you expected should work in languages like C# or other managed ones, but maybe this workaround gives you what you really wanted to get.

I want a dynamic static field

I've got a class A with a public field b
class A
{
public static string b;
}
but now I want to make b dynamic so I call it anything. So I can make the class a DynamicObject
class A : DynamicObject
{
}
but I the compiler doesn't let me now call A.dynamicThing cos I have to instantiate A as dynamic.
How can I mangle c# further to make this work?
I don't belive you're going to find a way to make this work. It's not just the DynamicObject that makes things work. The declaration as a variable of the "dynamic" data type is what tells the compiler to actually use the DynamicObject base to resolve the member access. With static access direct to the class, you don't have that. So I really just don't think this is going to work in C# unless that changes in the future.
It's not possible right now with .NET 4
more information in this article.
I think I understand now - the closest you can get is by using an ExpandoObject :
dynamic foo = new ExpandoObject();
foo.somethinghere = "bar";
foo.dynamicThing = "baz";
Edit:
I don't think its possible to re-route the access to a static property of a class
to an expando object if the name of the property does not match - how would the compiler know that that's what you meant to do? You are getting a compile time error after all, not a runtime error.
From MSDN:
When a field, method, property, event,
operator, or constructor declaration
includes a static modifier, it
declares a static member. In addition,
a constant or type declaration
implicitly declares a static member.
Static members have the following
characteristics:
When a static member M is referenced in a member-access (Section 7.5.4)
of the form E.M, E must denote a type containing M.
...
public class FakeDynamicMethodInvoker : DynamicObject
{
// your code here
}
public class FakeDynamicWrapper<T>
{
static FakeDynamicWrapper()
{
DynamicStaticField = (dynamic)new FakeDynamicMethodInvoker();
}
public static T DynamicStaticField{ get; set; }
}
public class RealClassWithDynamicStaticField: FakeDynamicWrapper<dynamic>
{
}
somewhere in a code:
RealClassWithDynamicStaticField.DynamicStaticField.AnyMethod();
C# doesn't let you really rename variables to some dynamic name at runtime. Your question is mangled.
If you are wanting variable b to have a dynamic object at runtime, then use the dynamic keyword.
Example:
dynamic b = GetBValue();
b.SomeOperation(); // the type of "b" will be evaluated/chosen at runtime.
Old question but worth to answer :)
Static constructors are the answer to these problems.
https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx
public class MyClass
{
public static dynamic StaticDynamicObject;
static MyClass()
{
StaticDynamicObject = new ExpandoObject();
StaticDynamicObject.Prop = "woohoo!";
}
}

When NOT TO USE 'this' keyword?

Sorry for asking it again, there are already some questions about this keyword. But all of them tell the purpose of 'this'.
When do you use this keyword
C# when to use this keyword
Use of “this” keyword in formal parameters for static methods in C#
Proper usage of “this.” keyword in C#?
My question is when not to use 'this' keyword .
OR
Is it all right to use this keyword always in situation like the code
class RssReader
{
private XmlTextReader _rssReader;
private XmlDocument _rssDoc;
private XmlNodeList _xn;
protected XmlNodeList Item { get { return _xn; } }
public int Count { get { return _count; } }
public bool FetchFeed(String url)
{
this._rssReader = new XmlTextReader(url);
this._rssDoc = new XmlDocument();
_rssDoc.Load(_rssReader);
_xn = _rssDoc.SelectNodes("/rss/channel/item");
_count = _xn.Count;
return true;
}
}
here i have not used 'this' with "_xn" and "_count" also not with "_rssDoc.Load(_rssReader);" is it fine? Should i use "this" with all occurrences of class variables within the class?
Edit: Is it useless to use 'this' in a class for its own variables?
I always use this. I use the same naming convention for local variables and private fields and it makes the code much easier to read because it becomes obvious if the used identifier is a field or local variable.
Further it prevents the introduction of bugs by adding a new local variable that hides a field.
internal sealed class Foo
{
private Int32 bar = 42;
private void Bar()
{
// Uncommenting the following line will change the
// semantics of the method and probably introduce
// a bug.
//var bar = 123;
Console.WriteLine(bar);
// This statement will not be affected.
Console.WriteLine(this.bar);
}
}
This can be avoided by using different naming conventions for fields and local variables but I really dislike underscore prefixed names. The first character of a word is very important for its readability and an underscore is one of the worst possible choices.
this is almost always optional and does not need to be specified. If you want to be explicit that you are referring to a member, then use this. If you have a naming convention (such as naming all member fields something like _foo), then you really don't need to refer to them like this._foo.
It's a matter of personal taste (no performance penalty), but I find having the explicit this is harder to maintain and adds little value if you have a solid naming convention. Some people will only use this when calling a member method, e.g. this.Foo(_bar) instead of Foo(_bar), but again, I don't personally believe it adds much.
If you're working with existing code, follow the convention there, otherwise, pick whichever makes you the most productive and effective.
My rule of thumb: Never use 'this' when it is redundant. In this case, 'this' is redundant, so I would avoid it. A tool like ReSharper is very good at telling you when this is the case.
I always use this. to make it clear that I am referring to a class member, not a local variable.
I would try to be consistent, so that people don't get confused into thinking that the few you do the other way (apart from the way you normally pick) have some special significance.
If you don't use the _whatever naming convention for fields, then you should use this.whatever consistently because otherwise there will be problems when constructors take a whatever parameter and try to put in a whatever field.
It is fine. Especially since your class doesn't have a base class and the private fields are named appropriately. ReSharper considers this in your case to be redundant.
Should i use "this" with all occurrences of class variables within the class?
In your particular case, NO.
Consider however the following example:
class RssReader
{
private String url;
public bool FetchFeed (String url)
{
new XmlTextReader (url);
// vs.
new XmlTextReader (this.url);
return true;
}
}
Here you'll need to specify this to access the instance variable that has the same name as the method argument.
there is absolutely no reason not to use this. even redundancy is no reason not to use it, at all. You get the benefit of the intellisense box to safely complete your code and saves your time by selecting the right variable with the down-key and not to maul your keyboard all the time.
You may, but don't need to unless it's a method that takes arguments with the same names as your class vars (to distinguish them).
Well, as for me, 'this' looks really redundant when used with names starting with "_". This is absolutely legal in your example though.
Here is how I look at it. When you call a member (be it method, property or field) of a class as such like DoMyThing(); or return Property; within the instance scope, it's not necessary that you're calling an instance member. DoMyThing or Property can be static members too.
public class Abc
{
public static void Static()
{
}
public Xyz Instance;
public void Test() //instance scope
{
var xyz = Instance; //calls instance member
Static(); //calls static member
}
}
For both of them (static and instance) I've not prefixed anything. Actually my choices are:
do not prefix at all as above
public void Test()
{
var xyz = Instance;
Static();
}
prefix for instance members alone
public void Test()
{
var xyz = this.Instance; // prefixes 'this'
Static();
}
prefix for static members alone
public void Test()
{
var xyz = Instance;
Abc.Static(); //prefixes class
}
prefix in both cases
public void Test()
{
var xyz = this.Instance; // prefixes 'this'
Abc.Static(); //prefixes class
}
This answer is not to say one style is better than other. This is just personal preference. Each has its own claim for correctness and readability.
My take:
a. I for one do not like the inconsistent style of 2. and 3.
b. 1. has the advantage of being more readable for me. Prefixing makes it more about definition than intent.
c. 4. is all about correctness. It has the advantage of being extremely consistent, especially considering you would be forced to prefix for both instance and static members at some point anyway. This is even more important to consider when it comes to base keyword where if you dont prefix with base keyword for a base class member, then adding a member with the same name in current derived class will cause it to override the previous call, changing the whole dynamics.
Personally, I would go with 1. And use this or Abc sparingly when I'm forced to. It's more readable for me, a benefit for me that is good enough to compensate for the little inconsistency it might cause.
Whereas your code will work without ‘this’, it explicitly tells that you mean ‘this’ particular instance of the class. Some people find it easier to read, plus it can help avoid mistakes.
Imagine you made a mistake and wrote…
public string Name
{ get; private set; }
public Forest(string name)
{
name = Name; //these are written in the wrong order...
}
It’s an easy mistake to make given that it’s essentially the same word. Unfortunately the compiler will not catch it - it won’t throw an error. As a result your instance will be created but the property will not have its value assigned. On the other hand if you made the same mistake while using ‘this’…
public string Name
{ get; private set; }
public Forest(string name)
{
this.name = Name; //these are still written in the wrong order but with 'this' prefix...
}
the compiler will throw an error telling you that you are attempting to assign value to a non existent property.

Categories

Resources