C# Functions

Hi all, I'm trying to learn C#.  I've been developing in VB and VB.NET since VB4; but am having some trouble with simple concepts.

I have a class which is shown below.  It has one function in it at this time to check if a string is a date or not.  No errors in this; but when referencing it in the main form's load event I get errors.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    class CS_SYS
    {
       
        public bool IsDate(string inputDate)
        {
            DateTime dt;
            return DateTime.TryParse(inputDate, out dt);
        }



    }
}

The Load event is shown below..... the IsDate function doesn't exist in this context. Even my IF/Else statement is erroring out.

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class frmDATE : Form
    {
        public frmDATE()
        {
            InitializeComponent();
        }

        private void frmDATE_Load(object sender, EventArgs e)
        {
             bool result = IsDate(tmpvalue1);
             If (bool IsDate(tmpValue1)) = True
            {
                DTP.Value = tmpValue1;
            }                
            else
            {
                DTP.Checked = false;
            }

        }
    }
}
LVL 4
Thunder724Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
This works the same as it would in VB.NET:  you defined IsDate within a class named CS_SYS, and neither that method nor that class are marked static (VB.NET's Shared), so you require an instance of the class to be created before you can use that method. The method is an "instance method". So you would change it to:

namespace WindowsFormsApplication1
{
    public partial class frmDATE : Form
    {
        public frmDATE()
        {
            InitializeComponent();
        }

        private void frmDATE_Load(object sender, EventArgs e)
        {
             CS_SYS instance = new CS_SYS();
             
             bool result = instance.IsDate(tmpvalue1);
             
             if (bool IsDate(tmpValue1)) = True
            {
                DTP.Value = tmpValue1;
            }                
            else
            {
                DTP.Checked = false;
            }

        }
    }
}

Open in new window


Also keep in mind that C#, unlike VB.NET, is case-sensitive. If is not the same as if.
0
Thunder724Author Commented:
OK, this got it partially.
My IF statement is failing with the "True" being flagged as "does not exist in current context".
also my Public tmpvalue1 variable is erroring out with ""does not exist in current context".

private void frmDATE_Load(object sender, EventArgs e)
        {
            CS_SYS instance = new CS_SYS();

             bool result = instance.IsDate(tmpvalue1);
             If (result = True);
            {
                DTP.Value = tmpValue1;
            }                
            else
            {
                DTP.Checked = false;
            }

        }

I have another class that holds my variables as indicated below...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace WindowsFormsApplication1
{
    class CS_APP

    {
       
        public void ClearVars()
        {
            string tmpValue1 = "";
            string tmpValue2 = "";
            string tmpValue3 = "";
            string tmpValue4 = "";
            string tmpValue5 = "";
            string tmpValue6 = "";
            object tmpObj1 = null;
        }
    }
}
0
käµfm³d 👽Commented:
As I mentioned, C# is case sensitive. True does not exist in C#; true (lowercase) does.
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Fernando SotoRetiredCommented:
Hi Thunder724;

Please read the comments I added to the modified code below.

public partial class frmDATE : Form
{
    public frmDATE()
    {
        InitializeComponent();
    }

    private void frmDATE_Load(object sender, EventArgs e)
    {
        // Need to create an instance of the CS_SYS class in order to call any public functions in it.
        CS_SYS cssys = new CS_SYS();

        // In order to call IsDate you need to use a string as a variable or literal. Added this line
        string tmpValue1 = "28/28/2015";
        // In order to call IsDate you need to reference the class it is in. In this case cssys
        bool result = cssys.IsDate(tmpValue1);
        // bool is not required in below line will make the expression invalid
        // C# is case sensitive so use if and NOT If
        // In comparisions need to use == and NOT the assignment operator =.
        // The boolean values must be in the proper case so use true and NOT True
        // Watch the placement of the ) to make sure it is in the right place.
        if( cssys.IsDate(tmpValue1) == true )
        {
            // I don't know what class DTP is but I made it a the CheckBox control
            DTP.Text = tmpValue1;
        }                
        else
        {
            DTP.Checked = false;
        }

    }
}


// need to set the class to public so that it is visable through out the namespace
public class CS_SYS
{
    public bool IsDate(string inputDate)
    {
        DateTime dt;
        return DateTime.TryParse(inputDate, out dt);
    }

}

Open in new window

0
Thunder724Author Commented:
Thank you, that was very helpful.  My code now is still having a problem with the tmpvalue1 variable even after I explicitly set it....

Also the CS_SYS.IsDate(tmpValue1); part of the statement is erroring with "an object refrence is required...."

private void frmDATE_Load(object sender, EventArgs e)
        {
            CS_SYS cssys = new CS_SYS();

            string tmpValue1 = "01/01/2015";
            bool result = CS_SYS.IsDate(tmpValue1);
             if (result == true)
            {
                DTP.Value = tmpValue1;
            }                
            else
            {
                DTP.Checked = false;
            }

        }

Open in new window

0
Fernando SotoRetiredCommented:
From your code below you have instantiated CS_SYS into a variable cssys but when you tried to access IsDate you used the class name CS_SYS and not the instance variable name cssys, see code below.

CS_SYS cssys = new CS_SYS();

string tmpValue1 = "01/01/2015";
bool result = cssys.IsDate(tmpValue1);

Open in new window

0
Thunder724Author Commented:
So does that mean I always have to create an instance of the class the function/procedure is in as apposed to explicitly referencing it before the object?
0
Fernando SotoRetiredCommented:
In your case you need to always instantiate the class CS_SYS in order to get access the public properties of the class. That also means that to use the objects of that class you need to tell the run time where it is in, what instance, this prevents name clashing.
0
Thunder724Author Commented:
Ok, that makes sense; but what if, in my case, I'm trying to persist a couple variables; such as tmpValue1 through out the application.  I'm not seeming to be able to do that.  If in my form_load event I place

 GLOBAL gv = new GLOBAL();
 gv.tmpValue1 = "01/01/2015";

and then in my button press event I'm setting the variable and closing the form I have to place the
 GLOBAL gv = new GLOBAL();
again in this event.

Is there no way to reference the global variable through out the project or at least just once in the form?
0
Fernando SotoRetiredCommented:
Hi Thunder724;

You can use a static class with static members. This will allow this class and member to be shared, only one copy of it to be used through the namespace. If in an application you want it to be used in another namespace you will need to add the below namespace to that code by using a using namespace, in the below example using WindowsFormsApplication1; at the top of the code file.

Now to access the IsDate method use this CS_SYS.IsDate(inputDate);

namespace WindowsFormsApplication1
{
    public static class CS_SYS2
    {
        public static bool IsDate(string inputDate)
        {
            DateTime dt;
            return DateTime.TryParse(inputDate, out dt);
        }
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
This also leads into extension methods.

In VB.NET, to make an extension method you would do something like the following:
Module Module1
	Sub Main()
		Console.WriteLine("Is 04/25/2015 a valid date time? {0}", "04/25/2015".IsDateTime())
		Console.WriteLine("Is 'How now brown cow' a valid date time? {0}", "How now brown cow".IsDateTime())
		Console.ReadLine()
	End Sub
End Module

Module Extensions
	<System.Runtime.CompilerServices.Extension()> Public Function IsDateTime(ByVal source As String) As Boolean
		Dim result As DateTime = New DateTime()
		Return DateTime.TryParse(source, result)
	End Function
End Module

Open in new window

Which produces the following output -Capture.JPGIf we were to rewrite this in C#, we would come up with this:
using System;

namespace EE_Q28700822CSharp
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Is 04/25/2015 a valid date time? {0}", "04/25/2015".IsDateTime());
			Console.WriteLine("Is 'How now brown cow' a valid date time? {0}", "How now brown cow".IsDateTime());
			Console.ReadLine();
		}
	}

	static class Extensions
	{
		public static bool IsDateTime(this string source)
		{
			var result = new DateTime();
			return DateTime.TryParse(source, out result);
		}
	}
}

Open in new window

Which produces the same output as above.

In either case since it is a Module in VB.NET and a class in C#, we could call it and any static/shared methods by referencing:

VB.NET - Module.SharedMethodName()
C# - class.StaticMethodName()

-saige-
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.