Use regular expression from another method in C# - c#

I separated my RegularExpression() method from my validate() method that has all the if statements. How can I use my regex codes if it's separated like this?
I'm fairly new to programming, and I'm still learning how to use methods.
public void Validate()
{
RegularExpression();
if (PhoneNumber_Regex.IsMatch(PhonNumb_txBox.Text) == false)
{
MessageBox.Show("Invalid cellphone number");
}
if (Email_Regex.IsMatch(Email_txBox.Text) == false)
{
MessageBox.Show("Invalid E-Mail");
}
}
public RegularExpression(object PhoneNumber_Regex)
{
var PhoneNumber_Regex = new Regex(#"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
var Email_Regex = new Regex(#"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.");
}

Add a static class where you will declare your regular expressions:
public static class MyRegexps
{
public static readonly Regex PhoneNumber_Regex = new Regex(#"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
public static readonly Regex Email_Regex = new Regex(#"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.");
}
Then use them in your caller method:
if (MyRegexps.PhoneNumber_Regex.IsMatch(PhonNumb_txBox.Text) == false)
{
MessageBox.Show("Invalid cellphone number");
}

In
public RegularExpression(object PhoneNumber_Regex)
{
var PhoneNumber_Regex = new Regex(#"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
var Email_Regex = new Regex(#"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.");
}
You declare 2 variables - but scope means those variables dont exist outside that call, so, they arent available for use.
However, if as part of the class you declared
readonly Regex Email_Regex = new Regex(#"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.");
so you have a read only variable you could then use like you thought as part of any function within that class
if (Email_Regex.IsMatch(Email_txBox.Text) == false)
{
MessageBox.Show("Invalid cellphone number");
}

Should do something on this line.
public static class MyValidator
{
protected static PhoneNumberRegex = new Regex(#"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
protected static EmailRegex = new Regex(#"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.");
public static bool ValidatePhoneNumber(string strToMatch)
{
return PhoneNumberRegex.IsMatch(strToMatch);
}
public static bool ValidateEmail(string strToMatch)
{
return EmailRegex.IsMatch(strToMatch);
}
}
and then use it like this
if (!MyValidator.ValidatePhoneNumber(PhonNumb_txBox.Text))
{
MessageBox.Show("Invalid cellphone number");
}

While it's not the only way to share things between methods, in this particular case it would make sense to use class-level members.
Your regular expressions themselves are unlikely to change, and can probably be static.
Initialize them in a constructor so it's automatic instead of having to manually call the initializer.
This all adds up to something more like this:
public class MyClass
{
private static Regex PhoneNumber_Regex { get; set; }
private static Regex Email_Regex { get; set; }
static MyClass
{
PhoneNumber_Regex = new Regex(#"^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$");
Email_Regex = new Regex(#"^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$.");
}
public void Validate()
{
if (!PhoneNumber_Regex.IsMatch(PhonNumb_txBox.Text))
MessageBox.Show("Invalid cellphone number");
if (!Email_Regex.IsMatch(Email_txBox.Text))
MessageBox.Show("Invalid E-Mail");
}
}

Related

How to set up method variables to class object properties/values

Simply put how do you establish a connection between method variable decloration and connect it with class properties (or inner objects), lets say you have default or hard set values in a class like this (obviously they could be other types but for simplicity its set to strings) :
public class SampleClass
{
public string strA = "Something 1";
public string strB = "Something 2";
public string strC = "Something 3";
}
//think of it as a data layer where strings are pointers to dbSets
How do you leverage the same SampleClass in a method that allows ONLY pick of properties Method(property).
Easy sample that does what its supposed to:
public class ProccessClass
{
private string _dummyOut;
public ProccessClass Pick(string input)
{
this._dummyOut = input;
return this;
}
}
class Program
{
static void Main(string[] args)
{
var Test = new ProccessClass().Pick(new SampleClass().strB);
// we know this works and compiles and returns the strB
}
}
What would you have to convert to ommit the new instantiation and skip the class declaration (if possible but in theory should be doable)
new SampleClass().strB
needs to be just
strB
So how to get the final code to execute??
public class SampleClass
{
public string strA = "Something 1";
public string strB = "Something 2";
public string strC = "Something 3";
}
public class ProccessClass
{
private string _dummyOut;
public ProccessClass Pick(SampleClass sampleClass) //is it the variable declaration?
{
this._dummyOut = input;
return this;
}
}
class Program
{
static void Main(string[] args)
{
string Test = new ProccessClass().Pick(strB);
//so NO new keywords clean and easy set based on class provided above
}
}
Constructor and void setters but no go, the goal is to set the Hard relation ship between the method intake value and setters

How to clean up if else series

Work in C#, want to reduce if else series, entity have two property FromServiceID and ToServiceID ,suppose my ServiceClass instance have bellow information.How to clean up bellow code? any type of suggestion will be acceptable.
entity= new ServiceClass();
entity.FromServiceID=3
entity.ToServiceID=1
if (entity.FromServiceID == 1)
{
entity.1KWithdrawal();
}
else if (entity.FromServiceID == 2)
{
entity.10KWithdrawal();
}
else if (entity.FromServiceID == 3)
{
entity.BTWithdrawal();
}
if (entity.ToServiceID == 1)
{
entity.1KDeposit();
}
else if (entity.ToServiceID == 2)
{
entity.10KDeposit();
}
else if (entity.ToServiceID == 3)
{
entity.BTDeposit();
}
public class ServiceClass
{
public int FromServiceID { get; set; }
public int ToServiceID { get; set; }
public void 1KWithdrawal()
{ Console.WriteLine("One_KWithdrawal"); }
public void 10KWithdrawal()
{ Console.WriteLine("Ten_KWithdrawal"); }
public void BTWithdrawal()
{ Console.WriteLine("BTWithdrawal"); }
public void 1KDeposit()
{ Console.WriteLine("One_KDeposit"); }
public void 10KDeposit()
{ Console.WriteLine("Ten_KDeposit"); }
public void BTDeposit()
{ Console.WriteLine("Ten_KDeposit"); }
}
Use a Dictionary. Something like this:
Dictionary<int, ServiceClass> dictionary = new Dictionary<int, ServiceClass>()
{
{1, new ServiceClass()},
{2, new ServiceClass()},
{3, new BTWithdrawal()},//assume BTWithdrawal inherits from ServiceClass
};
An example of how using it:
ServiceClass value=new ServiceClass();
value.FromServiceId=1;
value.ToServiceId = 2;
dictionary.TryGetValue(value.FromServiceId, out value);
//or dictionary.TryGetValue(value.ToServiceId, out value);
if (value != null) MessageBox.Show(value.Id.ToString());
Maybe this is an overkill, but you can create a class for each one of your cases that inherits from a common interface (let's call it ICommon) that exposes a common method for each case (in your case a Create method) and then inject that interface in the constructor of ServiceClass.
Then when you want to use ServiceClass, you will have to provide an actual implementation of ICommon (one of the classes you extracted from each case) and finally you only have to call entity.Create.
I believe this is the strategy pattern, that in summary says that you should extract an algorithm in a different class under a common interface.
Finally, this refactoring will reduce the cyclotomic complexity of your code (this mainly means that you reduce the branching on your code) which always a good thing.
What you could do is to put all the variations into an enum and call the enum values exactly like your methods that you would like to call. (I would suggest not to use numbers in the name, since the compiler won't allow it)
For the sake of simplicity and testability I put the enum and the methods into the same class:
public class ServiceClass
{
public enum ServiceID
{
OneKWithdrawal,
Ten_KWithdrawal,
BTWithdrawal,
OneKDeposit,
Ten_KDeposit,
BTDeposit
}
public ServiceID From_Ser_ID { get; set; }
public ServiceID To_Ser_ID { get; set; }
public void One_KWithdrawal()
{ Console.WriteLine("One_KWithdrawal"); }
public void Ten_KWithdrawal()
{ Console.WriteLine("Ten_KWithdrawal"); }
public void BTWithdrawal()
{ Console.WriteLine("BTWithdrawal"); }
public void One_KDeposit()
{ Console.WriteLine("One_KDeposit"); }
public void Ten_KDeposit()
{ Console.WriteLine("Ten_KDeposit"); }
}
This would be the method that would execute your if-condition methods. It uses reflection to access the methods that are coded in the enum. You probably have to adjust the object parameter in the Invoke(sc, null); call depending on where your methods are situated. If they are in the same class as where you would call execute you can use this.
public static void execute(ServiceClass sc)
{
sc.GetType().GetMethod(sc.From_Ser_ID.ToString()).Invoke(sc, null);
sc.GetType().GetMethod(sc.To_Ser_ID.ToString()).Invoke(sc, null);
}
And here you can test the entire code:
public static void Main(string[] args)
{
ServiceClass entity = new ServiceClass();
entity.From_Ser_ID = ServiceClass.ServiceID.BTWithdrawal;
entity.To_Ser_ID = ServiceClass.ServiceID.Ten_KDeposit;
execute(entity);
}
So you would end up with an enum and 2 lines of code.
You can use switch case as below:
var entity = new ServiceClass();
entity.FromServiceID = 3;
entity.ToServiceID = 1;
switch(entity.FromServiceID)
{
case 1:
new 1KWithdrawal();
break;
case 2:
new 10KWithdrawal();
break;
case 3:
new BTWithdrawal();
break;
}
switch(entity.ToServiceID)
{
case 1:
new 1KDeposit();
break;
case 2:
new 10KDeposit();
break;
case 3:
new BTDeposit();
break;
}

Error on static Class

public class Program
{
public static void Main(string[] args)
{
var c = check.myValue("Example 1"); //This is the pattern I've to use, don't want to create an object (Is it possible to use it with static class)
Console.WriteLine(c.result1);
Console.WriteLine(c.result2);
}
}
public static class check
{
public static void myValue(string qr)
{
public string result1 = "My Name" + qr;
public string result1 = "You're" + qr;
}
}
See here Online Example (Code is not working)
Every thing on main function I've to use exactly the same pattern because I'll use it in a lot of different classes and I don't want to create object each and every time by using non-static class.
Please correct me if I'm wrong
There's a lot wrong with the syntax of that code, which #Sergey addresses in his answer.
You appear to want to return an instance of a class from a static method, and that class should contain two properties.
You can do that by creating the actual, nonstatic class containing the properties:
public class Check
{
public string Result1 { get; set; }
public string Result2 { get; set; }
}
Then return a new instance from the static method therein:
public static Check MyValue(string qr)
{
var result = new Check();
result.Result1 = "My Name" + qr;
result.Result2 = "You're" + qr;
return result;
}
However, you're saying in the comments in your code that you don't want to use an object.
In that case it appears you want to use static properties. That's generally not recommendable, but it would look like this:
public static class Check
{
public static string Result1 { get; set; }
public static string Result2 { get; set; }
public static void MyValue(string qr)
{
Result1 = "My Name" + qr;
Result2 = "You're" + qr;
}
}
Then you can read Check.Result1 after calling the method MyValue().
Your code is totally wrong
myValue method returns void. You cannot assign void return value to variable.
You cannot have public modifiers for local variables.
You cannot have local variables with same name in same scope
If you want to return two values from method, then you should return object with two fields - custom class or tuple. You can also use out parameters, but I don't think it's your case
public static class Check
{
public static Tuple<string, string> MyValue(string qr)
{
return Tuple.Create($"My Name {qr}", $"You're {qr}");
}
}
With C# 7 it's a little bit better. You can write this method in one line and provide names for tuple properties
(string MyName, string YourName) MyValue(string qr) => ($"My Name {qr}", $"You're {qr}");
Usage
var result = Check.MyValue("Example 1");
Console.WriteLine(result.Item1); // result.MyName
Console.WriteLine(result.Item2); // result.YourName
You can practice with creating custom class with nicely named properties instead of using tuples.

How to best design a class that might contain null object

I'm about to design a class that more often then not will contain a reference to a Null value. It reminded me of nullable Datetime which has a boolean value to indicate if there is an actual value stored.
DateTime? dt = new DateTime?();
if(dt.HasValue)
{
//DoStuff
}
Is it a good coding practice to design a class as follows?
class Computer
{
public string Name;
public string ID;
//...
public bool IsHiveMind;
public HiveMindInfo RegInfo;
}
class HiveMindInfo
{
string SecretLocation;
int BaudRate;
int Port;
}
...and to use it...
Computer aComputer = GetComputer(...);
if(aComputer.IsHiveMind)
{
Network.DoHostileTakeOver(aComputer); //!
}
How about this code below?
It seems you can remove IsHiveMind variable since HiveMindInfo variable has the same meaning by checking its null or not.
class Computer
{
public string Name;
public string ID;
public HiveMindInfo RegInfo;
}
class HiveMindInfo
{
string SecretLocation;
int BaudRate;
int Port;
}
Computer aComputer = GetComputer(...);
if (aComputer != null && aComputer.RegInfo != null)
{
Network.DoHostileTakeOver(aComputer);
}
To answer your question, you could implement the code as proposed.
An alternative would be to consider the following design patterns:
Proxy Design Pattern
Strategy Design Pattern
Sample Code
interface ITakeOverStrategy
{
void Execute();
}
class KevinFlynnHackerStrategy : ITakeOverStrategy
{
public void Execute()
{
// a nod to Tron
}
}
class NeoHackerStrategy: ITakeOverStrategy
{
private readonly HiveMindInfo _hiveMindInfo;
public NeoHackerStrategy(HiveMindInfo info)
{
_hiveMindInfo = info;
}
public void Execute()
{
// Mr. Anderson!
}
}
// This is a surrogate class.
// ... The value returned by String.Empty is often used as a surrogate.
class IdleStrategy : ITakeOverStrategy
{
public void Execute()
{
// do nothing
}
}
class Computer
{
private readonly ITakeOverStrategy _takeoverStrategy ;
public Computer(ITakeOverStrategy strategy)
{
_takeoverStrategy = strategy;
}
public Subjugate()
{
// insert epic code here
_takeoverStrategy.Execute();
}
}
Then somewhere in your code you create an instance of Computer with the appropriate strategy:
var info = new HiveMindInfo();
// update instance parameters
var computer = new Computer(new NeoHackerStrategy(info));
computer.Subjugate();
UPDATES
August 13th, 2015 # 10:13 EST
My comment about structs is not within the scope of the original question, and has been removed:
If your classes are only going to contain fields/properties then I would consider converting them into struct.
Just add ? to your object:
class Computer
{
public string Name;
public string ID;
//...
public HiveMindInfo? RegInfo;
}
struct HiveMindInfo
{
string SecretLocation;
int BaudRate;
int Port;
}
And then check it exactly as you did with datetime:
Computer aComputer = GetComputer(...);
if (aComputer.RegInfo.HasValue)
{
// Do something
}

Manage a list of Constants

In several projects, we have a list of constant values in the database. These each have a table, name, and a GUID value. For example a Ticket Status table might have 3 values, "Open", "Closed" and "Hold". In our C# code a framework generates a C# file, as follows.
public class TicketStatus {
public static Guid Open = new Guid( "7ae15a71-6514-4559-8ea6-06b9ddc7a59a");
public static Guid Closed = new Guid( "41f81283-57f9-4bda-a03c-f632bd4d1628");
public static Guid Hold = new Guid( "41bcc323-258f-4e58-95be-e995a78d2ca8");
}; // end of TicketStatus
This allows us to write some clean(ish) code that sets ticket status as follows
ticket.strStatus = TicketStatus.Open.ToString();
While this works:
- It produces pretty clean C# code that's easy to ready and maintain
- It's supported by Intellisense
it's still clumsy, in that
- We have to continually convert to string for many operations
- The use of GUIDs seems like overkill.
- We cannot write a "normal" switch statement
// This won't compile
switch( strStatus ) {
case TicketStatus.Open:
case TicketStatus.Closed:
// do some stuff.
break;
}
The code was originally implemented with a bunch of GUIDs, to manage the case when a database would return the values in all upper case.
The question: What's the best way to code these constant values, so that it supports IntelliSense and switch statements?
Thanks Kirk,
Here's the string solution that I'm using.
public static class TicketStatus {
public const string Open = "7ae15a71-6514-4559-8ea6-06b9ddc7a59a";
public const string Closed = "41f81283-57f9-4bda-a03c-f632bd4d1628";
public const string Hold = "41bcc323-258f-4e58-95be-e995a78d2ca8";
}; // end of TicketStatus
string strTemp = TicketStatus.Open;
switch (strTemp) {
case TicketStatus.Open:
strTemp = "Jackpot";
break;
}
Preamble
I do really think, that you should stick to this for as long as you can.
public static class TicketStatus {
public const string Open = "7ae15a71-6514-4559-8ea6-06b9ddc7a59a";
public const string Closed = "41f81283-57f9-4bda-a03c-f632bd4d1628";
public const string Hold = "41bcc323-258f-4e58-95be-e995a78d2ca8";
}; // end of TicketStatus
If you want some magic :)
There is a solution, that nobody has mentioned here. You can use attributes to assign custom values to enumerations. You need to define an attribute and some helper class:
[AttributeUsage(AttributeTargets.Field)]
public class GuidValue : Attribute
{
public Guid Guid
{
get;
private set;
}
public GuidValue(Guid guid)
{
this.Guid = guid;
}
public GuidValue(string stringGuid)
{
this.Guid = new Guid(stringGuid);
}
}
public static class GuidBackedEnums
{
private static Guid GetGuid(Type type, string name)
{
return type.GetField(name).GetCustomAttribute<GuidValue>().Guid;
}
public static Guid GetGuid(Enum enumValue)
{
Type type = enumValue.GetType();
if (!type.IsEnum)
throw new Exception();
return GetGuid(type, enumValue.ToString());
}
public static T CreateFromGuid<T>(Guid guid)
{
Type type = typeof(T);
if (!type.IsEnum)
throw new Exception();
foreach (var value in Enum.GetValues(type))
{
if (guid == GetGuid(type, value.ToString()))
return (T)value;
}
throw new Exception();
}
}
And then you can use it in the following way:
enum TicketStatus
{
[GuidValue("7ae15a71-6514-4559-8ea6-06b9ddc7a59a")]
Open,
[GuidValue("41f81283-57f9-4bda-a03c-f632bd4d1628")]
Closed,
[GuidValue("41bcc323-258f-4e58-95be-e995a78d2ca8")]
Hold
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GuidBackedEnums.CreateFromGuid<TicketStatus>(new Guid("41f81283-57f9-4bda-a03c-f632bd4d1628")));
Console.WriteLine(GuidBackedEnums.GetGuid(TicketStatus.Hold));
}
}
And, of course, TicketStatus is an ordinary enum. So you can use it in switch statements.
I would use a java-like enum and some reflection. Here's an example C# implementation. It my not work with a switch, but it will quickly identify for you the required object.
using System;
using System.Reflection;
using System.Linq;
public class TicketStatus
{
private string _guid;
private TicketStatus(string guid)
{
_guid = guid;
}
public string GuidValue {get {return _guid; } }
public static readonly TicketStatus Open = new TicketStatus("7ae15a71-6514-4559-8ea6-06b9ddc7a59a");
public static readonly TicketStatus Closed = new TicketStatus("41f81283-57f9-4bda-a03c-f632bd4d1628");
public static readonly TicketStatus Hold = new TicketStatus("41bcc323-258f-4e58-95be-e995a78d2ca8");
//Reads all static readonly fields and selects the one who has the specified GUID
public static TicketStatus Identify(string guid)
{
var ticket = typeof(TicketStatus).GetFields()
.Where(x => (x.IsStatic == true) && (x.IsInitOnly == true) )
.Select(x => x.GetValue(null))
.SingleOrDefault(x => (x as TicketStatus).GuidValue == guid)
as TicketStatus;
return ticket;
}
}
public class Program
{
public static void Main()
{
var guid = "7ae15a71-6514-4559-8ea6-06b9ddc7a59a";
var ticket = TicketStatus.Identify(guid);
if(ticket != null)
{
Console.WriteLine(ticket.GuidValue + " found");
}
else
{
Console.WriteLine("unknown ticket");
}
}
}
try this
public static Guid Open = new Guid("7ae15a71-6514-4559-8ea6-06b9ddc7a59a");
public static Guid Closed = new Guid("41f81283-57f9-4bda-a03c-f632bd4d1628");
public static Guid Hold = new Guid("41bcc323-258f-4e58-95be-e995a78d2ca8");
public enum Status1
{
Open,
Close,
Hold
}
public static Dictionary<Guid, Status1> Dic = new Dictionary<Guid, Status1>()
{
{Open , Status1.Open},
{Closed , Status1.Close},
{Hold , Status1.Hold}
};
and then
var a = TicketStatus.Closed;
var label = TicketStatus.Dic.FirstOrDefault(e => e.Key == a).Value;
switch (label)
{
case TicketStatus.Status1.Close:
}
to keep your code more readable

Categories

Resources