Search code examples
c#classregistryreturn-value

c# how can return value from class?


I have class !

class Reg_v_no_string
{
    public static string key_place = "";
    public static string key = "";
    public static string value = "";
    public string reg_value(string key_place, string key)
    {
        string value = string.Empty;

            RegistryKey klase = Registry.CurrentUser;
            klase = klase.OpenSubKey(key_place);
            value = klase.GetValue(key).ToString();
            klase.Close();

        return value;
    }
}

and this returns blank message box. How can solve this problem !? Thanks !

how can i return value from this class ?

I tryed

private void kryptonButton1_Click(object sender, EventArgs e)
    {
        Reg_v_no_string.key_place = @"Control Panel\Desktop";
        Reg_v_no_string.key_place = "WheelScrollLines";
        MessageBox.Show(Reg_v_no_string.value);

    }

Solution

  • You need to actually call the method:

    private void kryptonButton1_Click(object sender, EventArgs e) 
    { 
        var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");
        MessageBox.Show(value); 
    } 
    

    Also consider some changes to your class:

    public static class Reg_v_no_string 
    { 
        public static string reg_value(string key_place, string key) 
        { 
            string value = string.Empty; 
    
             RegistryKey klase = Registry.CurrentUser; 
             // todo: add some error checking to make sure the key is opened, etc.
             klase = klase.OpenSubKey(key_place); 
             value = klase.GetValue(key).ToString(); 
             klase.Close(); 
    
            return value; 
        } 
    } 
    

    And then when you call this static class it is like this:

    // you don't need to `new` this class if it is static:
    var value = Reg_v_no_string.reg_value(@"Control Panel\Desktop", "WheelScrollLines");
    

    Or, to keep it so that it is not static:

    public class Reg_v_no_string 
    { 
        public string reg_value(string key_place, string key) 
        { 
            string value = string.Empty; 
    
             RegistryKey klase = Registry.CurrentUser; 
             // todo: add some error checking to make sure the key is opened, etc.
             klase = klase.OpenSubKey(key_place); 
             value = klase.GetValue(key).ToString(); 
             klase.Close(); 
    
            return value; 
        } 
    } 
    

    Then call it like this:

    Reg_v_no_string obj = new Reg_v_no_string ();
    var value = reg_value(@"Control Panel\Desktop", "WheelScrollLines");