mehir mehta
mehir mehta

Reputation: 3

Why my delegate programs giving me an error?

I tried this program it's working fine.

class MyProgram
{
    delegate string StrMode(string s);

    static string ReplaceSpace(string s)
    {
        return s.Replace(' ', '-');
    }
    static void Main()
    {
        Console.WriteLine("This is a Method Group Conversion example.");

        StrMode sm = ReplaceSpace;
        string str1 = sm("This is a test.");
        Console.WriteLine(str1);
    }
}

The above program gives me the nicest output, But i thought to make something new to which two classes could tend to call using the delegates method as i do below the programs but that makes me SICK and giving me unkind of invoking errors, please help, i want to play delegates using two class, So is that possible?

delegate string StrMod(string s);

public class MyProgram1
{
    public static string ReverseString(string s)
    {
        string temp = "";
        int i, j;
        for (j = 0, i = s.Length - 1; i >= 0; i--, j++)            
            temp = temp + s[i];

        return temp;
    }
}

public class MyProgram2
{
    public static string RemoveSpace(string s)
    {
        string temp = "";
        for (int i = 0; i < s.Length; i++)            
            if (s[i] != ' ')
                temp = temp + s[i];

        return temp;
    }
}

class MainProgram
{
    public static void Main(string[] args)
    {
        //creating an object for class 1..
        MyProgram1 mp1 = new MyProgram1();
        string str;

        StrMod str = mp1.ReverseString;
        string str2 = str("This is test.");
        Console.WriteLine(str2);
    }
}

Edited

Here is my error:

enter image description here

Upvotes: 0

Views: 84

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You already defined local variable with name str. You cannot use same name for delegate variable:

string str; // first definition    
StrMod str = mp1.ReverseString; // same name (also another issue - see below)

After you changed question, reason of error is that your ReverseString method is static, but you are using it as instance method. You don't need to create and use instance of MyProgram1 class. You should use class name to access static members:

StrMod str = MyProgram1.ReverseString;

BTW error message is pretty self-descriptive:

Member 'MyProgram1.ReverseString(string)' cannot be accessed with an instance reference; qualify it with a type name instead

It even has a hint of what you should do to fix error.

Upvotes: 1

Related Questions