i am trying to instatiate a public sealed class in my program,
the thing is, ...as i am still fresh C# .net not-yet Developer , i find this issue a little difficult ...
As for the problem in Question, you can skip straight to Program example, or read the folowing background:
DB_Schema is a helper namespace, i've Created, to deal with the data accessing
(it holds tables And SPs names ..etc')
one of its classes(below) deals with Stored Procedures, and this one holds names of SPs Parameters
public sealed class SProc
{
public sealed class GetCPAReport
{
public const string RecordNum = "#RecordNum",
CPAColumnName = "#CPAColumn_Name",
Value = "#value",
IsFreelance = "#isFreelance";
}
}
Usage in program:
within method for data access via SP
private DataTable Get_RefTable_OfUsersBy(string DepartmetID)
{
SProc.GetCPAReport SProcGetCpa = SProc.GetCPAReport();
SP_Params.Add(new SqlParameter(SProcGetCpa.IsFreelance, 1));
}
trying to access one of the instance (SProcGetCpa) members is not possible the way i tried .
i could just make class SProc + it's sub class UpdateCPAReport not sealed and ...
but as i was searching the question "can sealed class be instantiated?
well.. the answer is Yes ... though trying to find information on the error:
cannot be accessed with an instance reference; qualify it with a type name instead
yields no results, Nor an Example of Accessing Instantiated sealed class public member code
atleast not for fresh .net C#arpers like me
- Update
i wanted to avoid long lines and make custom short names for the strings that represents the stored procedure name
instead of
ParListEmployeeUsrs.SP_Params.Add(new SqlParameter(HTSPs.RobTC_CPA_Users_Names_JobPosition.IsFreelance, SelectedDepartmentID));
update 2
for future comers on this subject who seeks for an answer
as suggested by a dear friend of ours, here in StackOverflow
if you do have to make a short namings for your classes, when using them for current peoject :
just place this among the usings of your project
using system...
using restOf.net
//just add your own as follows !
using shortClassName = myHelperNameSpace.MyIncrediblyUnnecessaryLongHelperClassName;
GetCPAReport doesn't have any instance members. const members are implicitly static. In C#, you can't access static members through a reference as you're trying to at the moment.
You just want:
SP_Params.Add(new SqlParameter(SProc.GetCPAReport.IsFreelance, 1));
Personally I'd make GetCPAReport a static class, too. There's no point in instantiating it, as it just contains constants... so actively prevent it from being instantiated.
Related
cant quite understand how class work
class Class1{
private int a;
for(a=0;a<10;a++){}
// how can a be out of scope?
}
and why i can do this
class Class1{
private int a;
void tera()
{
private string aiha="lk"; //commenting this out ,makes it work why??
for(a=0;a<10;a++){}
}
}
1st part : can a class have only methods and fields? why?
2nd part: cant methods have declarations?
i know this might be a poor explanation but i cant wrap my head around .
For the first part, you haven't defined a method name so it wont work, you can't place the method's body inside a class without declaring a method.
class Class1{
private int a = 0;
void Example() {
for(a=0;a<10;a++){}
}
}
Would work
For the second part, it wouldn't make sense as variable is only available inside the method's scope so its meaningless to give it a modifier.
You can read more about classes here but basically its a group of members and methods that are usually gonna be used every time you create an instance of that class.
1st.
(Classes are basic constructs of .NET Framework.)
Because it's object oriented it can only contain MEMBERS like methods, fields, constants, properties, and events as single units .
(note: also members must be declared within a type).
2nd
In C# there are no global variables or methods as there are in some other languages.
and i think since c# considers a method as a single object you cannot try give different access to its variables, it will think you are trying to create another member for the class.
A little background: I'm new to C# and Unity, but catching on very quickly. I'm also hoping this thread will not spark a debate about the merits of classes and abstract coding, as that debate is unrelated and well-worn (and unnecessarily heated); so please keep that in mind.
I'm simply wondering if every C# script in Unity is required to have a main class in any way or for any reason.
Or instead, can methods, and variables can be written outside of a class in a blank file (with namespaces) to be used in a video game?
I'm asking because, when I create a new C# script, it seems to force a class into my file and I'm afraid of breaking things.
I hope to keep code abstraction to a minimum, and the current project
I'm working on has several situations where a class is not needed, or
only one instance of the class will be used. I'd like to simply avoid
using classes in those cases.
In terms of declaring/defining variables and methods outside of any class, you can't really do that in C#. It just isn't how the language was designed (the answers to the question I linked to expand on that idea, so I won't duplicate them here).
You're not without options, though; if you have a number of variables or methods that need to be accessible from different places and don't need an object reference, you can make them static, so you won't need to instantiate the class to make use of them:
public class UtilityClass
{
public static float GravityConstant = 3.51f;
public static string GameName = "MyFirstGame";
public static float CalculateProduct(float a, float b)
{
return a * b;
}
}
Then, you can reference the class's methods/members by accessing it through its name:
float product = UtilityClass.CalculateProduct(6, 1.5f);
An example of where you might use this pattern is when defining mathematical formulae which aren't included in Unity's Mathf methods, and using them in multiple classes.
Additional note: Creating a new C# script through Unity's editor UI will default to declaring a class of the same name that inherits from Monobehaviour. You can alter it to remove the inheritance from Monobehaviour if you don't need any of the methods/attributes of the class, which avoids unnecessary overhead. One example for this would be with a static class that you never need to instantiate.
Yes, you are.
In C#, things like global variables and functions just do not exist. Everything must be contained in a class.
"But what should I do in order to declare some stuff that can be accessed everywhere, without creating an object?" you asked. There is something called the static modifier. You can access the methods or variables or fields or properties marked with this modifier without creating an object of that class.
You just add the word static in a method and it becomes a static method! How simple!
Let's see an example.
I have this non-static method:
public class MyClass {
public void DoStuff () {
}
}
I can call it like this:
var obj = new MyClass();
obj.DoStuff();
But if I modify it with static,
public class MyClass {
public static void DoStuff () {
}
}
I can call it like this:
MyClass.DoStuff();
How convenient!
Note:
Please do not misuse the static modifier! Only use it when it makes sense! When? When the method is a utility method or when the method does not belong to individual objects but the class itself.
First of All you need to check where Methods define as offical
docs stated
"Methods are declared in a class or struct by specifying the access
level such as public or private...."
So, Method should be declare in a Class or struct and A given class
should be, ideally, responsible for just one task.(see also)
Your this question "Or instead, can methods, and variables can be
written outside of a class in a blank file (with namespaces) to be
used in a video game?" answer is hidden in the below question.
Can there be stand alone functions in C# without a Class?
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
You have to make a class in order to use methods or its variable
either instance class or static class.
Am I required to use Classes for every script? Every script means you required a class. Unity Support Component Based
Architectural Design and if you require any script related
work then you definitely require a script component which means a
class require.
Finally for singleton, thanks to Unity3dWiki great detail
available. I think you will be feel comfortable to code and writing
class if you keep in mind component based architecture of Unity3d.
Singleton vs Static: I will also recommend to check this: Why do you use a Singleton class
if a Static class serves the purpose
Hope it will help.
[Note: If this helpful Any one can update this answer for future reference and use].
I’m very new to programming. Actually less than one month back, I couldn’t name even 3 programming languages. So I’m really new to this.
After I understood the class concept and the object concept in OOP in general, I then realised that every single item present in the whole program is either an object or a class ready to give off objects.
Classes are non other than descriptions of objects, which are the main and sole players.
Moreover, functions or method are non other than sort of behavioural manifestation of an existing object.
( I wonder if the code line that we write for a function to be executed, the line of code in itself is a new object that refers to the existing original object that will perform the function we want , as part of its behaviour )
Now, If what I mentioned was near to be correct, What confused me next in my journey to understand OOP as a world wherein every single item is an object being utilised or destroyed, or brought into existence out of a class (blueprint ), which is nothing but a modifiable written description for objects how to be born.
What confused me here is the nature of “system”, “console”, and “namespace” each one of these, is it an object, so that we can call and utilise it without instantiating, or they are special classes readily instantiated as the program runs, or just ordinary classes ( which contradicts everything I understood ), because I can see "system" and "console" called and utilised only, and never instantiated ( just like an object )
Now, namespace seems to be a class that is instantiated into an object in the written script: ( namespace "the application name" { } ) but neither "system" nor "console" seems to be instantiated by programmer!
System is a namespace, Console is a static class inside the namespace System.
Static classes are classes which do not need to be created with the new keyword, and there is only one instance per application (excluding templated static classes - which you don't need to worry about for the moment)
Console can be written like this:
namespace System { //Namespace defined here!
public static class Console { //Static class defined here!
public static void WriteLine() { //Static method defined here!
//Implementation goes here
}
}
}
Note the keyword static when declaring the class. Removing this keyword would turn it into a normal class, and you'd have to use it like this:
var console = new System.Console();
console.WriteLine();
Based on the comments from Bauss and Physician about static methods.
You can write this, as well:
public class MyClass
{
public static void DoSomethingStatically()
{
}
public void DoSomethingNormally()
{
}
}
Now, you can do this:
MyClass.DoSomethingStatically();
but you cannot do:
MyClass.DoSomethingNormally();
To use the second method, you must create an instance:
var myClass = new MyClass();
myClass.DoSomethingNormally();
Note:
You cannot call a static method on an instance, so it is invalid to do the following:
var myClass = new MyClass();
myClass.DoSomethingStatically();
You can think of namespaces as containers of classes. System is a namespace which contains the Console class. Console is a special kind of class called a static class. A static class is denoted by the static keyword. The Console class's declaration would look something like this:
namespace System {
public static class Console {
//lots of stuff...
}
}
Actually you can read the Console class's source code in http://referencesource.microsoft.com
A static class cannot be instantiated. It just does its own work. It doesn't have objects. One of reasons is that it doesn't make sense to have objects. For example, the Math class is a static class because it doesn't make sense to say "Let's create a Math object!". Because Math is not like Cows or Streams or BinaryFormatters, which all are non static classes Generally, anything that you can prefix with "a" is not static. "a Stream", "a BinaryFormatter" etc.
Now for the namespace concept. You know sometimes the same word may mean different stuff depending on the context. e.g. Stream, in a programming context it means a file stream or some other kind of streams. But in a casual conversation, you say stream to mean a stream of water or something like that. So now you have to create two stream classes but there's a name conflict! That's why we have namespaces. Let's look at a real example. There are at least 2 classes called Path, but they are in different namespaces so it's ok to have the same name. One is in the System.Drawing namespace and the other is in the System.IO namespace. We often refer to those two classes as "System.IO.Path" and "System.Drawing.Path". Or you can write using directives.
Conclusion:
Both System and Console are not objects. They are a namespace and a static class respectively. And the word namespace denotes a namespace so it's not an object either.
I have created folders in my project named Classes, Forms, and Models.
Let's say my project is named ABC, so the folder hierarchy is:
ABC
Classes
Forms
Models
In \Models\, I have a class named ApplicationModel.cs, which contains a public method named GetApplications().
However, when I call that method from elsewhere in the same ABC project, I get, "The name 'GetApplications' does not exist in the current context"
I've added:
using ABC.Models;
to the calling class, but it makes no difference. I right-clicked GetApplications() to hopefully see "Resolve" there, but no go.
What must I do to access my own public method?
It would be helpful to see the definition of GetApplications() and the code that's attempting to call it, but I assume it's either a static or an instance method of the ApplicationModel class. In either case, you may have made your code aware of the namespace of the ApplicationModel class with the using statement, but the method must either be called on the class or an instance of the class, like so:
If GetApplications is a static method,
var applications = ApplicationModel.GetApplications();
If it's an instance method:
var appModel = new ApplicationModel(); // or, retrieve the instance from elsewhere...
var applications = appModel.GetApplications();
One way or another, you must refer to the class containing GetApplications in order to call it. If this doesn't help you solve the problem, please edit your question to contain the definition of the method, and the calling code.
Sounds like you're using a static function. Did you forget the static keyword?
A static function "runs" from a class, not an object:
public static string[] GetApplications()
It is hard to give definitive advice without some code on how you are trying to call that method. I can think of two possible ways:
either you are trying to call the method via the ApplicationModel class(ApplicationModel.GetApplications()), in which case you need to declare the method static
or you need to call the method on an object, but you are using the type -- in this case declare/create an object of type ApplicationModel and call the method on that object; (e.g. ApplicationModel model = new ApplicationModel(); model.GetApplications();)
Looks like the class is not marked as public.
You class should be
namespace ABC
{
namespace Models
{
public class ApplicationModel //class needs to be public is accessed outside the namespace
{
}
}
}
I have been following a workshop whilst I'm learning C#.
One of the class exercises that was given was to create a program that prints your name out into the console.
I have developed this.
My questions is .. is putting other classes into the main class a bad programming practice? I figure I'd ask before I started making habits! Should I just create a seperate class, incase I want to expand it to an actual project?
class Exercise1
{
static void Main()
{
Character myCharacter = new Character();
myCharacter.name = "tekaC";
Console.WriteLine("Hello {0}!", myCharacter.name); //Prints the character's name into the Console output
}
}
class Character
{
public string name;
}
It's not clear whether you mean:
Nesting one class within another
Keeping two top-level classes within the same source file
The latter is almost always a bad idea - class Foo should almost always be declared in Foo.cs so that it's easy to find. There are exceptions to this - for example, in Noda Time I have several delegates declared in a single file called Delegates.cs, but that's a special case - there's no code involved, and once you know that if you want to find any delegate, you look in Delegates.cs, it's fine.
Nested classes are fine when used appropriately - but I would default to creating new top-level classes. I rarely use nested classes unless they're meant to be implementation details which only the containing class is interested in. I usually make them private for exactly that reason - none of the rest of the code in the project needs to know about them at all.
One other point about your current code: you've got a public field, which is generally poor encapsulation. You should use a property instead, so that you can hide the implementation details. You probably want to give the Character class a constructor which takes the name at construction time too - you could then potentially make the underlying field readonly. For example:
// You may not want it to be internal, and you may not want it to be sealed -
// but you should think about both decisions.
internal sealed class Character
{
private readonly string name;
internal Character(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
internal string Name { get { return name; } }
}
You haven't put a class in another class at all! You've just put 2 classes in the same file, which is really a personal preference. (I have some files with 5-6 interelated classes edit: omg Jon Skeet disagrees with me oh noez! :) ).
So in your example, you have 2 classes.
Do you mean the two classes are in one file?
One class per file is generally accepted as the way to do it, and in some languages is necessary.