What must I do to access my own public method? - c#

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
{
}
}
}

Related

CS0051 Inconsistent accessibility: parameter type 'CharityDbContext' is less accessible than method 'Campaign.Campaign(CharityDbContext)' [duplicate]

I'm trying to pass an object (a reference to the currently logged on user, basically) between two forms. At the moment, I have something along these lines in the login form:
private ACTInterface oActInterface;
public void button1_Click(object sender, EventArgs e)
{
oActInterface = new ACTInterface(#"\\actserver\Database\Premier.pad",this.textUser.Text,this.textPass.Text);
if (oActInterface.checkLoggedIn())
{
//user has authed against ACT, so we can carry on
clients oClientForm = new clients(oActInterface);
this.Hide();
oClientForm.Show();
}
else...
on the next form (clients), I have:
public partial class clients : Form
{
private ACTInterface oActInt {get; set;}
public clients(ACTInterface _oActInt)
...which results in me getting:
Error 1 Inconsistent accessibility:
parameter type 'support.ACTInterface' is less accessible than method
'support.clients.clients(support.ACTInterface)'
c:\work\net\backup\support\support\clients.cs 20 16 support
I don't really understand what the problem is - both fields are private, and accessed by the relevant public method from the form. Googling doesn't really help, as it just points towards one element being public and the other private, which isn't the case here.
Anybody help?
Constructor of public class clients is public but it has a parameter of type ACTInterface that is private (it is nested in a class?). You can't do that. You need to make ACTInterface at least as accessible as clients.
Make the class public.
class NewClass
{
}
is the same as:
internal class NewClass
{
}
so the class has to be public
If sounds like the type ACTInterface is not public, but is using the default accessibility of either internal (if it is top-level) or private (if it is nested in another type).
Giving the type the public modifier would fix it.
Another approach is to make both the type and the method internal, if that is your intent.
The issue is not the accessibility of the field (oActInterface), but rather of the type ACTInterface itself.
What is the accessibility of the type support.ACTInterface. The error suggests it is not public.
You cannot expose a public method signature where some of the parameter types of the signature are not public. It wouldn't be possible to call the method from outside since the caller couldn't construct the parameters required.
If you make support.ACTInterface public that will remove this error. Alternatively reduce the accessibility of the form method if possible.
parameter type 'support.ACTInterface' is less accessible than method
'support.clients.clients(support.ACTInterface)'
The error says 'support.ACTInterface' is less accessible because you have made the interface as private, at least make it internal or make it public.
The problem doesn't seem to be with the variable but rather with the declaration of ACTInterface. Is ACTInterface declared as internal by any chance?
When I received this error, I had a "helper" class that I did not declare as public that caused this issue inside of the class that used the "helper" class. Making the "helper" class public solved this error, as in:
public ServiceClass
{
public ServiceClass(HelperClass _helper)
{ }
}
public class HelperClass {} // Note the public HelperClass that solved my issue.
This may help someone else who encounters this.
You can get Parameter (class that have less accessibility) as object then convert it to your class by as keyword.
In my case I hadone class in a file and I was passing a instance of that class to the constructor of my form in another file.
The problem was had declared the class without the public modifier : class MyClass {}
I could have solved it by changing it to public class MyClass {}
If this error occurs when you want to use a classvariable in a new form, you should put the class definition in the
Formname.Designer.cs
instead of the Formname.cs file.
After updating my entity framework model, I found this error infecting several files in my solution. I simply right clicked on my .edmx file and my TT file and click "Run Custom Tool" and that had me right again after a restart of Visual Studio 2012.
All the answers that say make the type ActInterface as public are right. I am only putting this post to explicitly mention why that's an issue
If a parameter to your public class constructor is private or internal qualified class, it means you wont be able to create an object of that parameter class from outside of the assembly and when you cannot instantiate the parameter object, how can you call this constructor to instantiate an object of this class ?
Try making your constructor private like this:
private Foo newClass = new Foo();

Confusion with System.ApplicationId;

Reading and messing around to understand static classes and static methods and their differences with non static methods and their usage which i still don't get except maybe for the Main method which must not be made an instance(object) of a class.
Why if i try to use:
using static System.ApplicationId;
public class Program
{
static void Main()
{
Copy(SOMETHING)// Copy method doesn't exist
}
}
Then try to use a method from ApplicationId like Copy();
The IDE? can't find the method?
Doing the same with:
using static System.Console;
public class Program
{
static void Main()
{
Writeline("Hello"); // OK
}
}
Then try to find a method from Console like WriteLine();
It can find it and i can use it.
Why does that happen?
My understanding is That those are both static members? Isn't that the reason why i cant make instances of those 2 classes? Yet i can use the methods in the second example but not in the first one since it seems that it doesn't let me (error: copy() doesn't exist in the current context...).
The short answer is that you wouldn't use the static keyword in a using statement for non-static namespaces like System.ApplicationId
To use methods on a non-static (instance) class, you have to first make an instance of it using new. The tl;dr part followsTo avoid having to write out the namespace prefix System. every time you want to refer to ApplicationId, you can add
using System;
and then in the class, you can get to the someMethod() method with:
new ApplicationId().someMethod();
Now let's talk about static:
Before C# version 6, you just couldn't use a using statement on a static class, so to get access to a static method like
System.Console.WriteLine()
you'd first add the non-static parent (System) with
using System
and then refer to the static method using the namespace
Console.WriteLine
With the using static syntax, you add the 'Console.' part of the namespace once per class on the using statement like so:
`using static System.Console;`
and then you can use WriteLine() instead of Console.WriteLine. I have to guess that the WriteLine() method has got to be the most common use case for this functionality.
If you check out https://msdn.microsoft.com/en-us/library/system.console%28v=vs.110%29.aspx it shows that System.Console is a static class, so using static is appropriate there.
However, System.ApplicationId is non-static (see https://msdn.microsoft.com/en-us/library/system.applicationid%28v=vs.110%29.aspx) so you can't use using static.
The answer is simple, the methods in ApplicationId are not marked as static.
Let's see the difference between static and instance methods:
Static method:
Console.WriteLine();
******* *********
^ ^
class method
name name
Instance methods:
Random aRandomObject = new Random();
aRandomObject.Next();
************* ****
^ ^
name of an method
instance of name
Random
As you can see here, you need an instance of that class in order to use non-static methods. But for static methods, you don't need an instance.
The using static directive allows you to omit the class name when you call a static method.
"But why doesn't it allow us to call instance methods like this?" you asked. As I have said above, you need an instance to call instance methods. If you only write the method name to call the method, how can the compiler know what instance do you want to call it on?
ApplocationId is not a static class, so you need to create an instance of it.

Are System, console, Namespace classes or already instances?

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.

accessing an instantiated sealed class public member

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.

C# Beginner, writing/calling a Method

When we write a method, say an easy one like
void myMethod()
{
// code here
//
}
and we call it from within Main(), it's done essentially this way:
Program myProgram = new Program ();
myProgram.myMethod();
Obviously, myProgram is entirely arbitrary (taking into consideration, of course, coding conventions) but what's up with the reference to Program?
You are declaring your method myMethod inside a class called Program. Since your method is not a static method (i.e. it is not static void myMethod()) it requires an instance of Program in order to work. Therefore you need to create a new instance of Program in order to invoke myProgram.myMethod() on it. If myMethod were static, you could have called it simply by Program.myMethod() or, since you're already inside that class to begin with, myMethod() (since the current class name is implied for static methods).
Program is a class, which contains methods. By default the only method it contains is static void Main(...).
If you add your non-static method myMethod it doesn't belong to the class Program, but rather to instances of Program (called objects).
Static methods (like Main) can be called directly from the class:
Program.Main(...);
Non-static methods must be called from objects of the class:
Program program = new Program();
program.myMethod();
Classes are designed to group together like functionality. Program isn't a good place to put these. You should create other classes, and use them throughout your code.
By using classes you keep like code together, and provide a mechanism to reuse the same code over again from different places. You can create as many different instances of 'Program' as you like, from many different classes, and invoke the 'myMethod' method on each of them.
For instance you might have a ClassRoster and a Student class, which can be used like this in the ClassScheduler class:
ClassRoster roster = new ClassRoster();
Student studentOne = new Student();
studentOne.StudentId = "123456";
roster.EnrollStudent(studentOne);
Program is the type, that defines myMethod in your question. In C# methods are defined by types.
You can either call methods via an instance of the defining type or via the type itself (if the method is static). Since myMethod isn't static, you need an instance of the type Program to call it.
use this:
public void myMethod()
{
// code here
}
in main method:
Program myProgram = new Program();
myProgram.myMethod();
Thanks everyone.
I went back to my code; I added static in front of myMethod, and in doing so the Program myMethod = new Program() became unnecessary (uncompilable? illegal?), and it can be called simply by writing myMethod() Obviously I need to study up on what static does and how it affects methods/classes!
I'm actually only in week #3 of my .NET class... our instructor, while very smart, leaves something to be desired in the teacher category. The assigned text for the class is only so-so in my opinion, at least for me and how I learn (Programming C#, O'Reilly) This is a very good community, thanks!

Categories