locked
Functions in C#

    Question

  • Hi all, I was wondering if some could explain the differences in functions found in C#? Having come from a VB background I am finding that C# doesn't have things like Subs, ByRef, ByVal and Optional parameters however have comes across things like ref and out statements. Correct me when I am wrong if I am assuming the following please:

    The following declaration of a method cannot return anything:

    private void test(int param1)
    {
    //I could call methods from here.
    }


    The following declaration I could pass values to another method:

    private void MainMethod()
    {
    int myint = 5;
    test(myint);
    Messagebox.Show(myint); //Shows 15 as value was passed and incremented
    }

    private void test(ref int i)
    {
    i = i + 10;
    }


    The following declaration returns a value:

    private void MainMethod()
    {
    string a;
    a = test();
    Messagebox.Show(a); //Shows hello
    }

    private string test()
    {
    string s;
    s = "hello";
    return (s);
    }



    Thanks for all comments + suggestions much appreciated Smile
    Thursday, November 13, 2008 1:22 PM

Answers


  • Hey there,

     C# don't have functions cause c# is  an object oriented language and OOP don't have functions only methods, you're in the rigth way when wrinting c# code, all code that you posted are rigth .

     About Vb.net..Vb.net has functios cause even suporting OOP vb.net is not a native OOP language, vb.net comes from vb6 that doesn't suport OOP.

    C# u don't use ByVal cause by default the parameter are passed by value,when u want to pass a value by reference u just use "ref"...Subs are kind like voids...



    att;

    Thursday, November 13, 2008 1:49 PM
  • void means it doesn't return a value, it is void. So it is identical to Sub in VB. Functions are old terms, it is customary in .NET to refer to both Sub and Function as Methods.

     

    Additionally, see Passing Arrays Using ref and out  for a more detailed explanation.

     

    Thursday, November 13, 2008 2:24 PM
  • A method and a sub are essentially the same thing.

    private void TestMethod()    
    {

    }

    private tells us who can access it. 

    void tells us what it will return (void returns nothing)

    TestMethod is, of course, the name.

    If you want to create a method to return a value, you can tell it what to return:

    private string TestMetod() would return a string

    private int TestMethod() would return an int

    Or, you can use out and ref with a void:

    private void TestMethod(ref string a)
    {
        a = "whatever";
    }

    out is basically the same as ref, but ref has to be initialized before you pass it to a method.

    This means this will not work:
    string a;
    TestMethod(ref a);

    but this will:
    string a;
    TestMethod(out a);

    or this:
    string a = "a";
    TestMethod(ref a);


    Long story short, here's an example of how to put this together:

    void Main()
    {
        string a = "";
        Test1(ref a);
        Console.WriteLine(a);
       
         string b;
         Test2(out b);
         Console.WriteLine(b);

         Console.WriteLine(Test3());
    }

    private void Test1(ref string a)
    {
       a = "Test1";
    }

    private void Test2(out string b)
    {
       b = "Test2";
    }

    private string Test3()
    {
       return "Test3";
    }

    The output would be:
    Test1
    Test2
    Test3
    Thursday, November 13, 2008 2:41 PM

All replies


  • Hey there,

     C# don't have functions cause c# is  an object oriented language and OOP don't have functions only methods, you're in the rigth way when wrinting c# code, all code that you posted are rigth .

     About Vb.net..Vb.net has functios cause even suporting OOP vb.net is not a native OOP language, vb.net comes from vb6 that doesn't suport OOP.

    C# u don't use ByVal cause by default the parameter are passed by value,when u want to pass a value by reference u just use "ref"...Subs are kind like voids...



    att;

    Thursday, November 13, 2008 1:49 PM
  • Ah I see thanks for clearing that up for me. I had  an idea that void were kinda like subs as it didn't let me return anything. However, I came a method which had two parameters... one of the variables had the keywork ref attached to it and the other had out attached to it. What does the out keyword do and how would one use it and why?
    Thursday, November 13, 2008 1:53 PM
  • void means it doesn't return a value, it is void. So it is identical to Sub in VB. Functions are old terms, it is customary in .NET to refer to both Sub and Function as Methods.

     

    Additionally, see Passing Arrays Using ref and out  for a more detailed explanation.

     

    Thursday, November 13, 2008 2:24 PM
  • Thanks for the link Smile but while we're on the matter I noticed when I delcared a string the colour changes dependent on case of string. Is it different when I do

    a as String;
    b as string;

    Is there a difference between the two?
    Thursday, November 13, 2008 2:38 PM
  • A method and a sub are essentially the same thing.

    private void TestMethod()    
    {

    }

    private tells us who can access it. 

    void tells us what it will return (void returns nothing)

    TestMethod is, of course, the name.

    If you want to create a method to return a value, you can tell it what to return:

    private string TestMetod() would return a string

    private int TestMethod() would return an int

    Or, you can use out and ref with a void:

    private void TestMethod(ref string a)
    {
        a = "whatever";
    }

    out is basically the same as ref, but ref has to be initialized before you pass it to a method.

    This means this will not work:
    string a;
    TestMethod(ref a);

    but this will:
    string a;
    TestMethod(out a);

    or this:
    string a = "a";
    TestMethod(ref a);


    Long story short, here's an example of how to put this together:

    void Main()
    {
        string a = "";
        Test1(ref a);
        Console.WriteLine(a);
       
         string b;
         Test2(out b);
         Console.WriteLine(b);

         Console.WriteLine(Test3());
    }

    private void Test1(ref string a)
    {
       a = "Test1";
    }

    private void Test2(out string b)
    {
       b = "Test2";
    }

    private string Test3()
    {
       return "Test3";
    }

    The output would be:
    Test1
    Test2
    Test3
    Thursday, November 13, 2008 2:41 PM
  •  OnamC wrote:
    Thanks for the link but while we're on the matter I noticed when I delcared a string the colour changes dependent on case of string. Is it different when I do

    a as String;
    b as string;

    Is there a difference between the two?

     

    string is just an alias for System.String, no difference

    Thursday, November 13, 2008 3:35 PM
  • By the way, C# doesn't have Optional parameters. That is strictly a VB thing. We use method overloading to accomplish this.

     

    Thursday, November 13, 2008 3:53 PM
  • Here is an example of each

     

     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    namespace MyConsoleApplication {

    class Program {

    static void Main() {

    Console.ForegroundColor = ConsoleColor.Green;

    Console.WindowHeight = Console.LargestWindowHeight;

    Console.WriteLine("*** The Return Project ***");

     

    string MyAnswer;

     

    //*** Using an output parameter - page 109 ***

    MyMethodOutput(out MyAnswer);

    Console.WriteLine(string.Concat("\n",MyAnswer));

     

    //*** Using a return from a Method - page 108 ***

    MyAnswer = MyMethodReturn();

    Console.WriteLine("\n\n" + MyAnswer);

     

    //*** Using a return from a Method in line - page 108 ***

    Console.WriteLine("\nInline {0}", MyMethodReturn());

     

    //*** Using a get from a property - page 167 ***

    MyAnswer = MyProperty;

    Console.WriteLine("\n\n" + MyAnswer);

     

    Console.ReadLine();

    }

     

    static public void MyMethodOutput ( out string ParmValue){

    ParmValue = "Answer from the Method using an output parm";

    }

     

    public static string MyMethodReturn (){

    return "Answer from the Method using the return";

    }

     

    static public string MyProperty{

    get { return "Answer from the property"; }

    }

    }

    }

    Thursday, November 13, 2008 7:04 PM
  •  JohnGrove wrote:
    By the way, C# doesn't have Optional parameters. That is strictly a VB thing. We use method overloading to accomplish this.

     

    FYI:  I believe that C# 4.0 will have this feature.

     

    Chris

    Thursday, November 13, 2008 7:27 PM
  • Do you have the link that confirms that Chris?

    Thursday, November 13, 2008 8:32 PM
  •  OnamC wrote:
    Thanks for the link but while we're on the matter I noticed when I delcared a string the colour changes dependent on case of string. Is it different when I do

    a as String;
    b as string;

    Is there a difference between the two?

     

    Nice colors. huh?  Welcome to C#.  As John noted there is essentially no difference between the two declarations.  In C#, case matters.  VB does not care about case.  The dark blue is a keyword,  The cyan is a type name.  I wish VB did the same.

     

    What is an alias?  An alias is a compiler feature that does not make much of difference with strings.  What the alias does is use the default definition for the type for the target platform.  This difference is most apparent with int.

     

    int num1 = 0;

    Int16 num2 = 0;

    Int32 num3 = 0;

    Int64 num4 = 0;

     

    In these declarations, int uses the default word size for the target machine.  This could be 32 bits or 64 bits for most machines still running today.  I do not think there any 16 bit machines out there that can run .NET, as most of them had hard drives with only a couple of GB of storage space and RAM that maxed out at 64MB like my old NT Server.  But, it remains for backwards compatability.

     

    Rudedog   =|^D

    Friday, November 14, 2008 12:07 AM
  •  Kassiano wrote:

    Hey there,

     C# don't have functions cause c# is  an object oriented language and OOP don't have functions only methods, you're in the rigth way when wrinting c# code, all code that you posted are rigth .

     About Vb.net..Vb.net has functios cause even suporting OOP vb.net is not a native OOP language, vb.net comes from vb6 that doesn't suport OOP.

    C# u don't use ByVal cause by default the parameter are passed by value,when u want to pass a value by reference u just use "ref"...Subs are kind like voids...



    att;

    VisualBasic goes back a lot further than that, but I would tend to agree with you....from a certain point of view. 

     

    To the OP,

    There are two ways to use VisualBasic.  You can use it as its' roots in BASIC allow you to, and never need to know or learn anything about .NET.  This means using all of those wonderful "keywords" and "functions" that find their roots in BASIC.  (Note the spelling.)  BASIC was a procedure driven language from a day when procedure driven languages were the school of thought.

     

    Then something happened.  An architect wrote a book, and a group of programmers must have read it.  GoF, Gang of Four, was born.  So they wrote a book, too.  All about Object Oriented Programming Design Patterns and OOP took off like a rocket.

     

    The other way to use VisualBasic is what describe as VB.NET usage, where you are basically doing the same stuff you would do in C#, Object Oriented Programming.

     

    Rudedog   =8^D   (I'm almost back to work, John.)

    Friday, November 14, 2008 12:22 AM
  • Int16 the alias is short

    int32 the alias is int

    Int64 the alias is long

     

    We are glad to have you back Rudedog!

    Friday, November 14, 2008 12:26 AM
  • Thanks all Smile I'm just glad the C# forum is more active than the VB one lol. I have found quite a few differences between VB and C# as I am beginning to use classes now. From the looks of things in C# I have to create a new instance of my class whereas in VB I was able to reference it directly. For instance:

    VB:             CL_Class1.SU_MySub()

    C#:             CL_Class1 cl_class1 = new CL_Class1();

             cl_class1.MyMethod();


    I am right in assuming the above? The other thing I noticed was that inheritance is shown via the use of colons but I thought if a class inherits from another class they are able to access its private methods? At the moment if I have:

    class CL_MyClass : CL_OtherClass //CL_MyClass inherits from CL_OtherClass

    When I create an instance of CL_OtherClass by doing CL_OtherClass cl_otherclass = new CL_OtherClass(); when I do cl_otherclass I could only access public methods... but whats the point of signifying inheritance as I could access these methods by not indicating inheritance?

    Please pardon my stupidity here (for any silly or obvious answers) but I am trying to get to grips with OOP properly as opposed to simply doing my assignment and handing it in. I want to know how to do things properly as opposed to simply asking for code. Once I get to grips with the basics before purchasing a book Smile
    Friday, November 14, 2008 9:25 AM
  • I promote a rule around here.  "Stupid questions are the ones that you DON'T ask."

     

    Code Snippet

    public class BaseClass

    {

    protected int baseField = 0;

    }

     

    class ClassB : BaseClass

    {

    public ClassB()

    {

    baseField = 1;

    }

    }

     

     

     

     

    When you declare stuff as 'private' it is meant to be just that, private and exclusively for the use by the class.  Now you could declare stuff as protected so that inheriting classes could access it, while instance objects would be denied access.

     

    Another interesting declaration is internal.  It will cause stuff to behave as if you declared it public throughout the current assembly.  But, external assemblies that tried to reference your compiled assembly would see it as private.  Or they wouldn't see it because it would behave as if it were private.

     

    Rudedog   =|^D

    Friday, November 14, 2008 12:44 PM
  • Thanks RudeDog Smile sometimes when I go to forums and ask such questions they say things that are discouraging but its nice to see posts like yours Smile
    Friday, November 14, 2008 1:17 PM
  • Not only is Rudedog a true gentleman but he is indeed a scholar.

     

    Friday, November 14, 2008 1:41 PM
  •  JohnGrove wrote:

    Do you have the link that confirms that Chris?

     

    http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686

     

    Chris

    Friday, November 14, 2008 10:57 PM