I am new to c# coding.
I have two classes: frmItem and commonFun
commonFun contains a method like this:
public static int convertint(string value)
{
int pass = 0;
try
{
if (value != "") Convert.ToInt32(value);
}
catch
{
}
return pass;
}
I want call this method to frmItem class.
You can call it by:
int intReturn = commonFun.convertint(yourStringHere);
That's it.
What you forgot in your convertint method, is to convert the value with a variable to set its value. change your code to this one:
public static int convertint(string value)
{
int pass = 0;
try
{
if (value != "")
{
/* --> */ pass = Convert.ToInt32(value);
}
}
catch
{
}
return pass;
}
Then, make sure the commonFun class is public
And after that, in commonFun code:
string textToConvert= //something
int convertedInt = frmItem.convertint(textToConvert);
Hope it helped!
By the way, why don't you just use the Convert.ToInt32() Method inside your code? because for me the convertint method looks quiet unnecessary.
Related
I'm a new C# programmer, and am wondering why I'm getting a object does not contain a definition of 'methodName' and no extension method 'methodName' accepting a first argument of type 'object' could be found error. I'm not sure why it seems the two classes aren't connected.
Here is the class with my method definitions:
namespace Simple_Restaurant_Simulation
{
class ChickenOrder
{
public int quantity;
public int GetQuantity(int ChickenQuantity)
{
this.quantity = ChickenQuantity;
return quantity;
}
public void CutUp()
{
return;
}
public void Cook()
{
return;
}
}
}
and the calling methods:
namespace Simple_Restaurant_Simulation
{
class Employees
{
public dynamic NewRequest(int Quantity, string MenuItem)
{
if (MenuItem == "Chicken")
{
return new ChickenOrder();
}
else
{
return new EggOrder();
}
}
public dynamic CopyRequest(dynamic MenuItem)
{
/*TODO:
if(existing order){
return existing order;
}
else { return "Whaddaya think I am, a miracle worker?"};
*/
return null;
}
public int Inspect(object Order)
{
int InspectResult = 0;
return InspectResult;
}
private string PrepareFood(object Order)
{
string PrepareResult = null;
try
{
if (Order is ChickenOrder)
{
for (int i=0; i < this.GetQuantity; i++)
{
Order.CutUp();
}
Order.Cook();
PrepareResult = "Chicken order has been cooked";
}
return PrepareResult;
}
catch (Exception)
{
}
}
}
}
Thanks for your help
I am not sure what you are trying to do here but the reason why the PrepareMethod doesn't compile is that it accepts an object and the object type obviously has no CutUp() method.
You could use the as operator to try to cast the Order object to a ChickenOrder:
ChickenOrder chickenOrder = Order as ChickenOrder;
if (chickenOrder != null)
{
for (int i = 0; i< this.GetQuantity; i++)
{
chickenOrder.CutUp();
}
chickenOrder.Cook();
PrepareResult = "Chicken order has been cooked";
}
Note that the cast will only succeed if the object that you are passing the PrepareFood method at runtime actually is a ChickenOrder. And for you to be able to pass a ChickenOrder object to a method that accepts an Order argument, the ChickenOrder class should inherit from Order:
class ChickenOrder : Order
{
...
}
Both EggOrder and ChickenOrder are specific types of orders that should inherit from the Order base class. This also means that you can change the return type of the NewRequest method from dynamic to Order and the type of the parameter that you are passing to the other methods from object to Order.
I implemented a code that read the value of a variable in a PLC. the value could be of whatever type (bool, string, int16, int32 and so on).
Actually I implemented this code using cast.
But now I saw that cast makes box/unboxing and that's a bad idea for a clean memory usage.
So I'm trying to make the same behavior but with a generic method type which is linked at run time.
So here is my code with the commentaries.
That works with all struct types(bool, int32) but not with class type (String), could you tell my what I missed so far.
namespace Template_String
{
class Program
{
public int num1 = 33;
public static string PLCstrvar = "PLCvarName";
static void Main(string[] args)
{
Console.WriteLine((Int32)Readwrite.READ(PLCstrvar));//working with cast
Console.WriteLine(Readwrite.READImp2<Int32>(PLCstrvar));//Working with generics
Console.WriteLine(Readwrite.READImp2<String>(PLCstrvar));//not working
}
}
public static class Readwrite
{
//the actual code
public static object READ(String PLCVariableName, Boolean WorkingDATA = false)
{//my code return an type object which is not really good regarding box / unbox implementation
//I'd like to do something like
String returnstr = FINDSYMBOL(PLCVariableName, WorkingDATA);
if (returnstr != "")
{
return _plcClient.ReadSymbol(returnstr);
}
return "";
}
//the projected code
public static T READImp2<T>(String PLCVariableName, Boolean WorkingDATA = false) where T : new()
{//The new code uses generics but that doesn't work with String as they are Class and not struct as Boolean are
//I'd like to do something like
dynamic returnstr = new T();//resolved in runtime
returnstr = FINDSYMBOL(PLCVariableName, WorkingDATA);
if (returnstr != "")
{
return(T)_plcClient.ReadSymbol(PLCVariableName);
}
return (T)false;//not good
}
public static String FINDSYMBOL(String strvalueToreach, Boolean WorkingDATA = false)
{
String StrValueToReach = "";
if (!WorkingDATA)
{
for (int inc = 2; inc < 10; inc++)
{
StrValueToReach = strvalueToreach;
if (_plcClient.SymbolExists(StrValueToReach))
{
return StrValueToReach;
}
else
{
return "null";
}
}
}
return "null";
}
}
/EDIT That is a black box developped by XY developpers far away from me. This code is only used to make the code running without their code !!/
public static class _plcClient //PLC dynamic link !!dummy code implemented elsewhere!!
{
/* this code return if the symbole exist and its value in Int32, Int16, String, Boolean.... type.*/
private static string nullable="";
public static bool SymbolExists(string value) { return true;}
public static object ReadSymbol(String value) { return nullable = "toto"; }
}
}
I wonder if there is a way to use a reference of a var like 'ref' but not in a method.
exemple :
using System;
using System.Collections;
using System.Collections.Generic;
public class Class3
{
struct myStruct
{
public bool structBool;
public int structInt;
public myStruct(bool _structBool, int _structInt)
{
structBool = _structBool;
structInt = _structInt;
}
}
myStruct currentTask;
int value1,value2;
bool mybool, isProcessing;
Queue<myStruct> myTask = new Queue<myStruct>();
void main()
{
//these two lines don't work due to the "ref" but I'm looking for something work like this
if (value1 > value2) myTask.Enqueue(new myStruct(mybool,ref value1));
if (value2 > value1) myTask.Enqueue(new myStruct(mybool,ref value2));
MyFunction();
}
void MyFunction()
{
if (myTask.Count > 0)
{
if (!isProcessing)
{
currentTask = myTask.Dequeue();
isProcessing = true;
}
else
{
currentTask.structInt++; // here I need to catch my var (value1 or value2)
}
}
}
}
I tried to put the values into an array but I think it's a bad way. I tried lot of other stuff but nothing work properly.
You can change the constructor to pass those parameters by reference like so:
public myStruct(bool _structBool, ref int _structInt),
The problem is that invoking this line
currentTask.structInt++;
still wouldn't change the original variables (value1, value2). Check the solution in the answer here: https://stackoverflow.com/a/13120988/775018
Usually when you want to give multiple values to a constructor (or even a method), it's very acceptable that you give them as part of a class:
public class Args
{
public int Value { get; set; }
}
So now you can do this:
Args args1 = new Args { Value = 10 };
Args args2 = new Args { Value = 34 };
// Obviously, your structs or classes should accept Args class as input parameter
var struct1 = new MyStruct(true, args1);
var struct2 = new MyStruct(false, args2);
Now modifications to Args.Value1 and/or Args.Value2 will be available for the struct constructor callers.
Suppose I have a C# class that has multiple properties that all look like this:
private bool _var1Dirty = true;
private Double? _var1;
public Double? Var1
{
get
{
if (_var1Dirty)
{
_var1 = Method_Var1();
_var1Dirty = false;
}
return _var1;
}
}
And the only differences between each of these properties would be:
The type of return var (in this case Double?, but could just as easily be int, string, etc)
The method call - Method_Var1() (Each property would have a different one)
Is there any way I could write this as a custom class?
Something along the lines of:
public class Prop
{
public delegate T Func();
private bool _dirty = true;
private T _val;
public T Val
{
get
{
if (_dirty)
{
_val = Func;
_dirty = false;
}
return _val;
}
}
}
And then I could pass into it the:
Return type T
Method Func
(PS - I know this won't compile / is dead wrong, but I wanted to give an idea of what I'm looking for)
Any help / guidance would be really appreciated.
Thanks!!!
You're close. You can do something along the lines of this:
public class Dirty<T>
{
public Dirty(Func<T> valueFactory)
{
this.valueFactory = valueFactory;
dirty = true;
}
private Func<T> valueFactory;
private bool dirty;
private T value;
public T Value
{
get
{
if (dirty)
{
value = valueFactory();
dirty = false;
}
return value;
}
}
}
And you consume it like this:
Dirty<double?> dirtyDouble = new Dirty<double?>(() => SomethingThatReturnsADouble());
double? value = dirtyDouble.Value;
I'm not sure what the dirty checking actually does, but if you need someone more complicated than a bool you can always turn it into some Func<T> the checks for dirtiness.
Edit:
Given #mikez comment and your answer, you can save yourself the creation of the Dirty<T> class by using the built in Lazy<T>, which also guarantess thread safety:
public class F
{
private Lazy<double?> lazyDouble = new Lazy<double?>(() =>
MethodThatReturnsNullableDouble(), true);
public double? Value
{
get
{
return lazyDouble.Value;
}
}
}
have a php code like this,going to convert it in to C#.
function isValid($n){
if (preg_match("/\d+/",$n) > 0 && $n<1000) {
return true;
}
return false;
}
Here is my try,BUT error shown Error is "expected class, delegate, enum, interface or struct error C#"
public string IsValidate(string Item)
{
string Result = Item;
try
{
Result = System.Text.RegularExpressions.Regex.Replace(InputTxt, #"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2");
}
catch(Exception ex)
{
console.WriteLine(ex.Message)
}
return Result;
}
What is the error,Is there any other way to implement this better than my try ?
i got this snippet from here code
You haven't define this method inside a class/struct that is why you are getting this error. You may define this method inside a class.
public class MyValidator
{
public string IsValidate(string Item)
{
//Your code here
}
}
Later you can use it like:
MyValidator validator = new MyValidator();
validator.IsValid("Your string");
Also you are missing semicolon at the end of the Console.Write statement, plus 'c' for Console should be in uppercase
Edit:
Since in your php code, it looks like you are trying to see if the string passed is an integer and it is less than 1000, you may use the int.TryParse like the following:
public class MyValidator
{
public bool IsValidate(string Item)
{
string Result = Item;
int val;
if (int.TryParse(Item, out val) && val > 0 && val < 1000)
{
return true;
}
else
{
return false;
}
}
}
In you main method you can do:
static void Main()
{
MyValidator validator = new MyValidator();
Console.WriteLine(validator.IsValidate("asdf123")); // This will print false
Console.WriteLine(validator.IsValidate("999")); //This will print true
Console.WriteLine(validator.IsValidate("1001")); //This will print false
}
In C# a method must be placed inside a class or struct:
public class Validator {
public string IsValidate(string item) {
...
}
}
In this case I would probably translate it like this:
public static class Validator {
public static bool IsValid(string item) {
int value;
return int.TryParse(item, out value)
&& value > 0 && value < 1000;
}
}
You could define your function inside a static class such that you dont have to create an instance of it before invoking the function. Like,
public static class Validator
{
public static string IsValidate(string item)
{
// ...
}
}
Then, you can call it using:
Validator.IsValidate("String to validate")
EDIT: You could then check that your function is returning what you expect by doing:
if(Validator.IsValidate("String to validate") == "Expected result")
{
/* Logic to be executed here */
}