How to access the method of other class in other namespace? [duplicate] - c#

This question already has answers here:
How to access namespace which is part of different project?
(2 answers)
Closed 8 years ago.
//Given below is the main program in a particular namespace and class.
using System;
namespace ConsoleApplication3
{
class Class1
{
static void Main()
{
Program pg = new Program();//this is the other class in other name space
pg.displayy(); //i want to use this function
Console.ReadLine();
}
}
}
// ---------------------------------------
// and other program name is : program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplicationexample2
{
class Program
{
void displayy()
{
int a = 6;
Console.WriteLine(a);
}
}
}

In case of a static method:
namespaceName.ClassName.MethodName ();
In case of a non-static method:
create an instance of the class by :
namespaceName.ClassName instance = new namespaceName.ClassName();
and then invoke the wanted method by:
instance.MethodName();

Add an using to the top of the ConsoleApplication3.cs file:
using ConsoleApplicationexample2;
And if the referenced class is in another project, also add a reference to that project to your other project. Right-click on the project in the Solution Explorer, and click Add Reference.

To be able to access method of other class both method and class must be public:
public class Program
{
public void displayy()
{
// your code here
}
}

Related

how to add multiple names spaces and Classes within those for one solution

As a first simple exercise, I ask you to create a new C# Console App in Visual Studio.
This app must have 2 different namespaces, and each namespace contain at least one class with a method to display the word "Hello, this is XXX class" in console, where XXX is the parent class. You can code it on the same file or create different files for different namespaces.
In the Main method of the default class called Program, you must be able to show all the different "Hello..." messages in console, being able to call different classes and methods you just have created.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace First
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello this is The FIRST Class.");
Console.ReadLine();
}
}
}
namespace Second
{
internal class Program
{
static void Main1(string[] args)
{
Console.WriteLine("Hello, this is the SECOND Class.");
Console.ReadLine();
}
}
}
I was hoping both Name spaces would show the individual classes. Not sure what I'm doing wrong here
You should be creating two classes and should call respective methods from Main method.
using First;
using Second;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
FirstClass fc = new FirstClass();
fc.DisplayHello();
SecondClass sc = new SecondClass();
sc.DisplayHello();
}
}
}
namespace First
{
internal class FirstClass
{
public void DisplayHello()
{
Console.WriteLine("Hello this is The FIRST Class.");
}
}
}
namespace Second
{
internal class SecondClass
{
public void DisplayHello()
{
Console.WriteLine("Hello this is The SECOND Class.");
}
}
}

C# error while calling class

I learned basic and now I want to learn OOP in C#
I have this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace uceni_cs
{
class Zdravic
{
public void pozdrav()
{
Console.WriteLine("Ahoj světe ! ");
}
}
}
But when I try to call it using this code
namespace uceni_cs
{
class Zdravic
{
public void pozdrav()
{
Console.WriteLine("Ahoj světe ! ");
}
}
Zdravic trida = new Zdravic();
}
In code Zdravic trida = new Zdravic();
is error. A namespace cannot directly contain members such as fields or methods.
What I am doing wrong ? I just want to call the class.
Thanks
In C# there is no such a thing global variable so you can't just create new instance of Zdravic type that does not belong to any class.
I suggest you to read General Structure of a C# Program, and c# Classes and Structs.
You need to create an entry point to your application and instantiate the class there.
class EntryPoint
{
static void Main()
{
Zdravic trida = new Zdravic();
trida.pozdrav();
}
}
Create your class object in main method and then use the class properties using that object.
Zdravic trida = new Zdravic();
in main method of you program/application.

Functions inside a static class need the name of the class to be called

I have a class named MyFillerClass in the file MyFillerClass.cs like so :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace trial
{
public static class MyFillerClass
{
public static List<string> returnCategoryNames()
{
List<string> catNames = new List<string>();
catNames.Add("one");
catNames.Add("two");
catNames.Add("three");
catNames.Add("Others");
return catNames;
}
}
}
now when i want to call it from somewhere else (like a form class) :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace trial
{
public partial class Form1 : Form
{
static string lastSelectedCategory;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.DataSource = returnCategoryNames(); //error : The name 'returnCategoryNames' does not exist in the current context
lastSelectedCategory = listBox1.SelectedValue.ToString();
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
lastSelectedCategory = listBox1.SelectedValue.ToString();
System.Diagnostics.Debug.Print("### User choosed " + lastSelectedCategory + " category");
}
}
}
the line "listBox1.DataSource = returnCategoryNames();" produce an error as indicated in the code ,to fix it i have to adjust it to "listBox1.DataSource = MyFillerClass.returnCategoryNames();".
the question is : in a long program that can add a lot of typing ,can i adjust the class MyFillerClass in such a way that i can just call the function like so : returnCategoryNames() ?
No, not in C# up to 5.0. You need to prefix the static method name with the class name.
However, in C# 6.0 there will be static using statements available. This new language feature will allow you to access directly static classes methods.
Yo can't do it in C# yet. To do it, you need to do a none static class and none static method.
You can do an extension method.
To call a function from a class you need to have an object created for that class then only you can call the method defined in the class.
In case of static class no need to create any object. you have to direct call the method followed by the class name.
In your case
MyFillerClass.returnCategoryNames();

Extension Methods with Custom Classes

I'm attempting to extend my custom classes and running into a problem where it cannot find the extension method.. I have and can extend any built in classes or even ones contained within DLL's. I don't know if this is a compilation error or if I'm doing something wrong. Threw together a small program for an example, won't compile..
Here's the extension:
namespace ExtensionMethodTesting.Extension
{
public static class Extension
{
public static void DoSomething(this ExtensionMethodTesting.Blah.CustomClass r)
{
}
}
}
Here's the Custom Class:
namespace ExtensionMethodTesting.Blah
{
public class CustomClass
{
public static void DoNothing()
{
}
}
}
Here's the code calling it:
using ExtensionMethodTesting.Blah;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExtensionMethodTesting.Extension;
namespace ExtensionMethodTesting
{
class Program
{
static void Main(string[] args)
{
CustomClass.DoNothing();
CustomClass.DoSomething();
}
}
}
I must be missing something... Anyways the exact error just for clarification is:
Error 1 'ExtensionMethodTesting.Blah.CustomClass' does not contain a definition for 'DoSomething' c:\users\damon\documents\visual studio 2013\Projects\ExtensionMethodTesting\ExtensionMethodTesting\Program.cs 16 25 ExtensionMethodTesting
Extension methods require an instance of an object. You'll have to new up a CustomClass to use it.
var custom = new CustomClass();
custom.DoSomething();
See this answer as to why that is.
You need to instantiate an object of the CustomClass to use its extension method.
CustomClass obj = new CustomClass();
obj.DoSomething();

How do I add common C# code to a Visual C# 2008 Express project/solution?

(I still feel like a complete newbie in MS Visual environments... so please bear with!)
I'm using Microsoft Visual C# 2008 Express Edition.
I have a project and in that project are two different forms. The .cs file for each form starts out:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyNameSpace
{
public partial class MyFormName : Form
{
...
(...and the second is "MyFormName2" but no differences besides that)
I want to write a function that I know both forms are going to need to access. I right-clicked on my project, selected "Add", selected "New Item" then selected "Code File" and named my file "Common.cs" and it gave me a completely blank file that's in my project.
How do I set this up...? I thought I should do the following...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyNameSpace
{
}
...but then when I try to add a function like:
public void mytestfunc() {
}
within that namespace I get the following error:
"Expected class, delegate, enum, interface, or struct"
How do I set things up so I can have "mytestfunc" be available to both MyFormName and MyFormName2?
Thanks!
-Adeena
UPDATE:
Understand (now) that everything must be in a class, but then I don't understand how to really use it. Does that mean I have to create an object? This common function happens to just be some math...
so now if I have this:
namespace MyNameSpace
{
public class MyCommonClass
{
public void testFunc()
{
MessageBox.Show("Hee hee!");
return;
}
}
}
...how do I call testFunc from my Form? Must I do the following:
MyCommonClass temp = new MyCommonClass;
temp.testFunc();
or is there another way to call testFunc?
If you do something like:
namespace MyNameSpace
{
public class myclass
{
public myMethod()
{
// Code
}
}
}
You will be able to instantiate and access it. If you change it to:
namespace MyNameSpace
{
public class myclass
{
public static myMethod()
{
// Code
}
}
}
You will be able to call myClass.myMethod without instantiating a new myClass.
The short answer is that everything needs to be inside a class; I'd suggest you sit down with a basic tutorial to help you get to grips with the basics...
Code need to be inside classes.
It would look something like this:
using System;
namespace MyNameSpace
{
public class CommonHelper
{
public string FormatMyData(object obj)
{
//do something
return String.Empty;
}
}
}
If the function you call is not related to the forms, make it static
namespace myns
{
public static class myhelper
{
public static void DoSomething()
{
}
}
}
and call the method using myhelper.DoSomething();
If the function you want to call is somehow form-related, e.g. common functionality across multiple forms, derive a class from Form (does not need a visual form) and make it base class of the visual forms:
namespace myns
{
public class MyFormBase : Form
{
protected void DoSomethingWithTheForm()
{
}
}
}
and in your form's .cs:
namespace myns
{
public partial class MyFormName : MyFormBase
{
}
}

Categories