Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Without constructor how you initialize a class variables ?
For Example , I have a class with two variables name as "x" and "y" data type as string. By creating an object for the class I need to initialize some value to these variables , without involvement of Constructor . Can u please any one help me ?
You can use the Object Initializer feature:
var obj = new yourclass { x = "abc", y = "xyz" };
Although, this will work only if the variable x and y are public. Or, in other words, if they are accessible to the code where you are instantiating the class.
You can put an initializer when you create the variables:
private string foo = "val1";
You can initialize the default values to private variables directly by initializing them as
public class A
{
private int X= 5; //Like this
private int Y= 6
}
You can do it just like with a local variable like this:
class MyClass
{
string x = "x";
string y = "y";
}
when you create an object for your class using new keyword default constructor will be invoked and all your class data members will be initialised to their default type values.
Ex:
Class Student
{
String strName;
String strAddress;
}
Student student1=new Student();//this will call default constructor
the above statement calls the Default Construdtor and it will initialise the values to their default types as below.
public Student
{
strName=String.Empty;
strAddress=String.Empty;
}
if you want to initialise your class variables with some specific values then you can create parameterised constructor or initialise them normally.
String x="some value";
String y="some value";
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 3 years ago.
Improve this question
Consider a simple class
public class MyClass
{
private int myProperty
...
public int MyProperty
{
get
{
return myProperty;
}
set
{
// some evaluation/condition
myProperty= value;
}
}
...
}
Now, if I want to create an empty constructor where I set default values for the class properties I could do this either this way:
public MyClass()
{
myProperty = 1;
...
}
or this way:
public MyClass()
{
MyProperty = 1;
...
}
Both examples seem valid, since I would never set a default value, that doesn't meet the requirements in the setter evaluation.
The question is, is there a best practice or doesn't it matter anyway?
What would be the advantage of one or the other be (as I can't find any)? Is there some reference, where this question is adressed?
So far I have come across code from many different developers that use either or both ways...
You can use both. But i prefer the first one. Why? Because the value that the property uses is directly assigned. For C# 6 above, you can use default value in a property directly without using constructor.
public class Person
{
public string FirstName { get; set; } = "<first_name>";
public string LastName { get; set; } = "<last_name">;
}
I personally like to set it as you done in first block.
For me it serve as additional fact of method is constructing object, not using alredy constructed. Also it makes me sure that properties is not called (they transform to set/get functions which results in couple of excess instruction).
But i believe that both variants are valid and maybe compiler optimizes properties to direct assignment.
For simple data first method is ok. But on more complex data, you could have a condition in the set (depending to another variable for example, set { if (Config.TestEnv) ...} so if you directly set the private value, you could be in trouble.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
A question I'm having trouble finding the answer to: When my class is instantiated, in what order are it's members instantiated.
For example, can I set a member to the value of a member lower in the declaration order? (See code example.)
// Can I do the following:
class foo
{
int A = B;
int B = 12;
}
// And this, for class types:
class bar
{
foo X = Y;
foo Y = new foo();
}
The order of field instantiation does not matter in this case. What matters is that you cannot use non-static field, method or property in the field initializer. So, it doesn't matter if you do:
class Foo
{
int A = B;
int B = 12;
}
or the opposite order
class Foo
{
int B = 12;
int A = B;
}
Your code will not compile anyway. You will get A field initialize cannot reference the non-static field, method, or property 'Foo.B' error.
So, you shouldn't worry about the order because this situation can never occur.
You just can't do it.
You will get the following compilation error :
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Program.foo.A' Test C:\Users\sebas\source\repos\Test\Test\Program.cs 14 Active
I you extend the question to static field, they are executed from the first to the latest one.
It can easily be tested with the following code :
class foo
{
public static int A = foo.B;
public static int B = 3;
public static int C = foo.B;
}
static void Main(string[] args)
{
Console.WriteLine(foo.A);
Console.WriteLine(foo.B);
Console.WriteLine(foo.C);
Console.ReadLine();
}
The result will be :
0
3
3
Anyway. Even if it was working, I would suggest that you just use a constructor. You will gain in maintainability.
Despite the bad example, it's worth understanding how initialization actually works. The draft C# 6.0 Spec has this to say about it:
The default value initialization described in Field initialization occurs for all fields, including fields that have variable initializers. Thus, when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order.
Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#field-initialization
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Is it possible to declare a variable inside a called function, and no external source can change this variable? For example:
private void SetVariable(){
privatetypevariable variable = "hello";
}
variable = "world"; //<-- doesnt work because it cannot access the variable 'variable' inside SetVariable()
How do I access the variable outside of the scope of the above method?
Instead of declaring the variable in the method define it as a class field. Then you can change it from anywhere inside the class. Fields are generally marked as private so it cannot be changed outside the class. If you want to expose it outside the class use a property instead with a public type.
private privatetype fielda;
void methodA(){
fielda = "hello";
}
void someOtherMethod()
{
fielda = fielda + " world";
}
It wouldn't be possible due to the fact that a variable only lives inside its given scope, as soon as you exit the scope, the variable is lost.
To add to that, you can't add visibility modifiers to your variables declared in a method
The below code won't work since s only lives in the scope of methodA() and is lost as soon as you exit the scope.
private void methodA(){
String s = "hello";
}
private void methodB(){
s = s + " world"; //even tho methodA created an s variable, it doesn't exist in the eyes of methodB
}
You could do something as follows:
class someClass{
private String s;
public someClass(){
s = "hello world";
}
public String getVariable(){ //you can read this variable, but you can't set it outside of this class.
return s;
}
}
If you specify a variable inside a function, it is scoped to only that function in C#.
Example 1:
private void foo(string bar)
{
string snark = "123";
}
private void derk()
{
snark = "456";
}
Example 1 would cause a compile error. If you mean inside a class, declare the property as readonly and it cannot be changed outside of it's initial constructor.
Example 2:
public class Lassy
{
private readonly string _collarColour;
public Lassy(string collarColour)
{
_collarColour = collarColour;
}
private void SetCollarColour(string newColour)
{
_collarColour = newColour;
}
}
Example 2 will also cause a compile error because you cannot assign to a readonly attribute in a class outside of it's initial constructor.
To achieve what you want, use readonly.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
private class global
{
public static string str = label4.Text;
int a = Convert.ToInt32(str);
}
private void button8_Click(object sender, EventArgs e)
{
string myString = label4.Text;
int Val = Int32.Parse(myString);
dataGridView1.Rows.Add(label2.Text, Val * global.a );
}
Hello guys I have some problem here, then I convert string to int in private void it works fine, but then I try to convert it on public global it shows errors, any ideas how to fix it?
DB2.Form2.global.a' is inaccessible due to its protection level
An object reference is required for the non-static field, method, or property 'DB2.Form2.global.a
An object reference is required for the non-static field, method, or property 'DB2.Form2.label4
a is not visible outside the class global, you should make it public:
public int a = Convert.ToInt32(str);
Since the global class is not marked as static you either make it static or create an instance of global.
private static class global
{
public static int a = ...
}
or when not making it static (but a must be public):
var myGlobal = new global();
int x = myGlobal.a;
Furthermore:
classes should be capitalized
public class Global { ... }
Same goes for public properties/fields:
public int A = 1;
public string Str = "";
a is not defined as a global static variable.
Redefine it as public static int a;
You can't access a field from a class without first instantiating an object unless that field is static and the field is accessible.
your int is private int your global class.
Change it to public and static.
a is not static and public. So either make it public static or instantiate the class and use the instance to access a.
private field can't be accessed outside of class.
variable a is private and hence not accessible outside the class and moreover it's declared as instance member and not static member.
you need to declare it as public static int a based on your posted code usage
Your class definition should look like
private class global
{
public static string str = label4.Text;
public static int a;
a = Convert.ToInt32(str);
}
First error is inaccessible due to its protection level cause because you declared a as private.
second error An object reference is required for the non-static field, method, or property caused because you were trying to access an instance member as static member.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
For example:
class WebCrawler
{
List<string> currentCrawlingSite;
List<string> sitesToCrawl;
RetrieveWebContent retwebcontent;
public WebCrawler()
{
}
}
When I make WebCrawler = new WebCrawler(parameter here)...
Add another constructor to your class;
public WebCrawler(parameter here)
{
}
After that, you need to remove parameterless one constructor, so people can create an instance of your class without provide any parameters.
You can create an instance of it like
WebCrawler w = new WebCrawler(parameter here);
You can read for more informations from Instance Constructors
Here is a DEMO.
Create constructor with parameter you want to be provided by user:
public WebCrawler(string param1, int param2)
{
}
When any constructor like that is added the default one (parameterless) is no longer available, unless you write it yourself:
public WebCrawler()
{
}
So just remove it, and user won't be able to create your class instance object without providing these parameters. You can also make the same setting parameterless constructor private or protected.
Instance Constructors (C# Programming Guide)
You can make the parameter-less constructor private...
private WebCrawler()
{
}
Meaning no consumers/callers have the ability to call it.
You then have only one constructor that they can use:
public WebCrawler(string something)
{
}
Add another constructor accepting a parameter:
public WebCrawler(string someParameter)
{
}