define get or set in c# - c#

friends i have problem with using get or set in class in c#
when i use get or set in gives error(invalid token { in class)
pls, see below code,i have this problem in it
static int abcd
{
get
{
return _abcd;
}
}
thanx
this is the complete code,i dont have this problem with any of your codes but just this:
namespace ConsoleApplication2
{
class Program
{
class Car
{
private int _speed;
public int Speed;
{
get
{
return _speed
}
}
}
}
}

The snippet you have posted is fine as it is, also in regards to the error, as it has the correct number of { to } and in the right order.
Look at where you have placed it (possibly outside of a class), or look for extra } in the file.
Update: (following edit in question)
Your issue is here:
public int Speed; // <-- ; should not be here
And:
return _speed // <-- missing the ;
The property should be implemented like this:
public int Speed
{
get
{
return _speed;
}
}

There are two errors in your code.
You have a semicolon where there shouldn't be one (spotted by Oded).
You are missing a semicolon where there should be one.
Try this instead:
namespace ConsoleApplication2
{
class Program
{
class Car
{
private int _speed;
public int Speed // <-- no semicolon here.
{
get
{
return _speed; // <-- here
}
}
}
}
}
I noticed that the code you originally posted was formatted badly. I would suggest that you format your document automatically in Visual Studio to make the braces line up. This should make the error more obvious. When the formatting of the code looks wrong you know that there is an error nearby. You can find this option in the menu: Edit -> Advanced -> Format Document or use the keyboard shortcut (Ctrl-E D for me, but might be different for you, depending on your settings).
I would also suggest that you consider using auto-implemented properties instead of writing the getter out in full:
namespace ConsoleApplication2
{
class Program
{
class Car
{
public int Speed { get; private set; }
}
}
}

This should work:
class Foo
{
static int _abcd;
static int Abcd
{
get { return _abcd; }
set { _abcd = value; }
}
}

Related

How do I fix when it says value assigned to it is never read in C#?

Hi I'm new in programming in c#, I just want to know how to fix this issue because I can't increment the value of the points in the game that I am making...
using UnityEngine;
public class GameManager: MonoBehaviour
{
private int point;
public void IncreaseScore()
{
point++;
}
}
view image
It's just a hint, so it doesn't stop you from run this code. However to fix, as information suggests you should read point property by for example assigning it to some value:
int someValue = point;
If you want this field to be obtainable by other classes in code, you can add public method for it and adding it will resolve your issue too:
using UnityEngine;
public class GameManager: MonoBehaviour
{
private int point;
public int GetScore() => point;
public void IncreaseScore()
{
point++;
}
}

How can I split my code (c#) in Visual Studio while maintaining full functionality?

I realize this sounds like a question the answer to which can be found in the first google link, but to my surprise it wasn't. I'm learning C# recently and for the first time I'm writing a fairly large project, which at the moment contains more than 200 lines of code and, according to my estimates, should contain more than 1000 in the end.
I understand that this is not a problem for experienced programmers, but I'm starting to get confused.I have found some answers on pulling classes from neighboring files, but my code consists almost entirely of methods and I have not been able to interpret these answers to my advantage. Again, this is most likely due to my inexperience.
i want my files to look something like this:
program1.cs
int x = 25;
program2.cs
Console.Write(x);
As you can see, this does not happen. I have tried adding the CS file either manually or through the solution explorer. Nothing helps, so I really hope to get an answer here. How can I get all methods and variables from one file to work in another in VS? Additional question: If there is no such possibility at all, can I somehow visually hide a piece of my code from myself, just so that it does not bother me until I need to change something in it?
P.S. Yes, I understand that if it is easy to get confused in the code, then the code is poorly composed. I'm also working in this direction, but I would still like to know the answer.
If your class is so big you want to split it into multiple files it’s likely that you should also be splitting it into multiple classes that each perform a simpler job. To access public methods and variables of one class from another class, either they need to be static (meaning there’s only ever one of that thing basically) in which case you can activate them using the name of the class, e.g.:
Class1.cs
public static int x = 25;
Class2.cs
Console.Write( Class1.x );
Or you need a reference to a specific instance of that class, e.g.
Class1.cs
public int x = 25;
Class2.cs
Class1 instance = new Class1();
Console.Write( instance.x );
Ok, so here is the code I promised.
Here are the two files I created
Program.cs
using System;
namespace splitClass
{
// You can either write a class here and use it on the other file
public class HelloThere
{
public HelloThere()
{
Console.WriteLine("Hello, there");
}
public static int add(int a, int b)
{
return a + b;
}
public int subtractFromTen(int c)
{
return 10 - c;
}
static void Main(string[] args)
{
// You can also use the class in the other file
UseHelloThere useHelloThere = new UseHelloThere();
Console.WriteLine(useHelloThere.add(8, 9));
}
}
// or split a class into two using partial keyword
public partial class SomeOtherClass
{
public int abc;
public SomeOtherClass()
{
abc = 87;
}
public int getAbc()
{
return abc;
}
public int add(int b)
{
return b + abc;
}
}
}
Other file.cs
using System;
namespace splitClass
{
// since namespaces are same, you can use the other class from the same file
public class UseHelloThere
{
HelloThere hello;
public UseHelloThere()
{
hello = new HelloThere();
}
public int add(int a, int b)
{
return HelloThere.add(a, b);
}
}
// or you can write the continuation of the other class
public partial class SomeOtherClass
{
public int subtract(int a)
{
return abc - a;
}
}
}
If you want to get all methods and variables from one file to work in another in VS, you can refer to the following steps:
First, define variables and methods in Program1.cs such as:
namespace ConsoleApp7
{
namespace ConsoleApp
{
public static class Program1
{
static void Main(string[] args)
{
}
public static int x = 25;
public static void add()
{
x++;
}
}
}
}
Second, add project reference in Program2.cs.
Finally add using in Program2.cs and then you can use the variables and methods defined in Program1.cs.
using ConsoleApp7.ConsoleApp;
class Program2
{
static void Main(string[] args)
{
Console.WriteLine(Program1.x);
Program1.add();
Console.WriteLine(Program1.x);
}
}

OOP how to do Class "folders"

what I want to do is:
Some script accessing:
//...
string Str = "aab";
void Update(){
GUI3D.Label(Str);
GUI3D.TextField(ref Str);
}
//...
in GUI3D script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class GUI3D {
static void Label(string Text){
// make text apear
}
static int CursorField;
static void TextField(ref string Text){
// changing cursor field depending on the inputs
// change text and make it apear
}
}
I hope I didn't strip down too much.
but what I want to do is that Only TextField can access the CursorField and noone else.
so that if I'd want to do:
static void Label(string Text){
// make text apear
CursorField = 0; // that I'd get error due to protection level.
}
how would I be doing that?
You have an architecture issue. You can't hide a class member from itself. You are telling your static GUI3D class to Label() something and you are also trying to hide data from itself? Why do you need to hide the data from one member function of your GUI3D class?
If you don't mind changing your architecture a bit, you could try a class like this ( forgive syntax errors, I don't have a compiler handy :D ):
public class MyLabel {
private string _text;
public string Text {
get { return _text; }
set { _text = value; CursorField = _text.Length; }
}
public int CursorField { get; private set; }
}
As baoghal said, you can't hide a class member from itself - so wrap that functionality in an auxiliary class & only let the class itself modify CursorField.

Deserializing with DataContract Collection<Class> to derived Class

The title is a bit confusing, hopefully someone maybe know's a better fitting title for my problem.
I am trying to create a class which derives from Collection<Classname> to implement an easy way to save and loading Configuration files. Writing to file is no problem, but I am not able to implement the deserialze function. I am unsure how to assign the deserialized content back to my instance.
Current approach:
[DataContract(Name = "Configurations", Namespace = "")]
public class Configurations : Collection<Configuration>
{
internal void SerializeToBinaryFile(string path)
{
Helper.DumpObjectToBinaryFile(this, path);
}
internal void DeserializeFromBinaryFile(string path)
{
// Getting Error:
// This expression can not be used as an assignment target
this = Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path);
}
}
I am familiar with this.Add([Configuration]) but this just gives the opportunity to insert one item. I thought about using a foreach(Configuration c in temporaryObject and add them one by one but this can't be the best solution.
Thanks for any hint!
Edit 1:
I've added the foreach iteration for adding the Configurations
internal void DeserializeFromBinaryFile(string path)
{
foreach (var c in Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path))
{
Add(c);
}
}
This seems to work fine. Does someone know a better pattern?
You cannot assign to new instance of class to "this" regardless if you are doing de-serialization or something else. Code bellow just uses new constructor and doesn't work either. Basically, you do have different 2 instances of class in memory at that point.
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public void CreatePoint(int x, int y)
{
// Doesn't work either
this = new Point();
}
}
You have to do this outside of the body of the class, so rather make static deserialization method:
[DataContract(Name = "Configurations", Namespace = "")]
public class Configurations : Collection<Configuration>
{
internal void SerializeToBinaryFile(string path)
{
Helper.DumpObjectToBinaryFile(this, path);
}
internal static Configurations DeserializeFromBinaryFile(string path)
{
return Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path);
}
}

Why does the C# compiler differentiates between these 2 cases?

When you have some property that's like:
using Algebra;
public Algebra.Vector3 Direction
{
get { return this.direction; }
}
then compile and later change it to:
using Algebra;
public Vector3 Direction
{
get { return this.direction; }
}
it seems like the compiled code is different between the two assemblies, which I could see using the Reflector.
Why does the compiler differentiates between the two code? Isn't it only necessary to see if there is any ambiguous type at compile time and if there isn't, have the compiled code be the same for both? I would assume the compiled code to use fully qualified names for every member at all times.
I can't reproduce this. Sample code:
namespace Algebra
{
public class Vector3 {}
}
namespace Test
{
using Algebra;
public class Program
{
private Vector3 direction = null;
public Vector3 Direction1
{
get { return direction; }
}
public Algebra.Vector3 Direction2
{
get { return direction; }
}
}
}
The generated IL for the two properties is exactly the same, and they look the same in reflector.
My guess is that you've actually got another class called Vector3 in the "global" namespace (or some other namespace that you have a using directive for).
Try hovering over both type names in Visual Studio and see what they show.
Here is an example that would generate the results you are observing. Hopefully this clears up what you’re asking. Assuming you have
a separate library containing the type Vector3 in a namespace Algebra;
the following files in your project:
File ①
namespace NotAlgebra
{
public class Vector3
{
// ...
}
}
File ②
using Algebra;
namespace NotAlgebra
{
public class XYZ
{
// Refers to NotAlgebra.Vector3 (defined in File 1 above)
Vector3 MyProperty1 { get; }
// Refers to Algebra.Vector3 (defined in the external library)
Algebra.Vector3 MyProperty2 { get; }
}
}

Categories