Guide for converting a JavaScript function with spread arguments of different types to C# style

I am having difficulty with the strict typing in C# when it comes to function arguments.

For my Reverse Polish Notation (RPN) calculator, the required arguments will be passed through a function call using a comma-separated list of different types:

this.FxMath.RPN(this.Mt, this.L, 2, '*', this.F, '*')   // (this.Mt are Variables as Objects)

The function itself will receive the comma-separated arguments as ...seq:

RPN(ergebnis: VariableUnitBuilder, ...seq: any) {

like this:

RPN(ergebnis: VariableUnitBuilder, ...seq: any) {

    let stack = [], i = 0;

    typeof seq[i] === 'object' ? seq[i] = seq[i].nominalValue : null;
    stack.push(seq[i]);
    i++;

    while (i <= seq.length) {

      typeof seq[i] === 'object' ? seq[i] = seq[i].nominalValue : null; // Extract number value or do nothing.
      let item = seq[i];  // Number or operator

      if (isNaN(item)) {
        let a: number;
        let b: number;

        switch (item) {
          case '+':
            a = parseFloat(stack.pop());
            b = parseFloat(stack.pop());
            stack.push(a + b);

            break; 
...... }

Now I need some arguments with different types and an unknown length:

(this.Mt, this.L, 2.5, '*', this.F, '*') // Class, Class, Double , String, Class, String

Answer №1

If you want a method to accept a flexible number of parameters, you can utilize the params modifier in conjunction with an array of System.Object:

public void RPN(VariableUnitBuilder p, params object[] seq)
{
   // ...
}

You can then make calls like these:

someInstance.RPN(someVariableUnitBuilder, 1, "2");
someInstance.RPN(someVariableUnitBuilder, 1, "2", 3, new object());

It's important to note that when dealing with value types, using this approach may lead to boxing, which could have unintended consequences.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

Modify the MUI time picker to display as a digital clock inside a DateTimePicker widget

I need to update my MUI DateTimePicker component to use the DigitalClock time picker instead of the Analog Clock picker. The current component has two steps, first picking the date from a calendar and then selecting the time. This change is only necessary ...

The type '{ id: string; }' cannot be assigned to the type 'DeepPartial<T>'

In my code, I am attempting to create a generic function that abstracts my repository infrastructure for creating a where clause. export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export int ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

Angular is failing to show any data on the display, despite there being no apparent errors

As a newcomer to Java and Angular, I am currently enrolled in a course on getting started with Angular. I have been attempting to display information in the navigator, but for some reason, nothing is showing up. Despite thoroughly checking my code, I could ...

What is the best way to include a DLL that may not be available at all times?

In our extensive C# software application, there is a need to integrate functionality from .NET DLLs belonging to a third-party software package. However, it's worth noting that not all of our clients will be utilizing this particular package. If I wer ...

Changing Colors Automatically with C# Programming

I am currently working on a project where I want the text color to change as different users add annotations to a document. Initially, I used predefined color values in C# and cycled through them as new annotations were added. This method works well and s ...

Solving Cross-Origin Request Sharing (CORS) Problem in

Encountered a CORS issue while attempting to send a post request to a C# web API. Here is the error message: Access to XMLHttpRequest at 'api url in different domain' from origin 'client url' has been blocked by CORS policy: Respon ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Issues encountered while attempting to convert HTML Image and Canvas Tags to PDF within Angular 2

I am currently facing an issue with my code. My requirement is to download HTML content as a PDF file. I have been successful in downloading text elements like the <p> tag, but I am encountering difficulties when trying to download images and canvas ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

Utilize Selenium WebDriver to wait for a timer based on its innerText

Hello, I am struggling to get this code to work and I could really use some assistance. Here is the HTML code: <span id="banner">Rolling in 10.00...</span> The "Rolling in 10.00..." text inside the span is a timer that counts down to 0. I am ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

The error message "Invalid Data Type: Not an Array - google charts" was encountered

I am struggling with an ajax call that I have set up. The issue arises when passing an array from the backend to the frontend. Upon checking the data through an alert on the frontend, everything seems fine. However, Google charts raises an error stating th ...

Incorporate a typescript library into your Angular application

Recently, I added a text editor called Jodit to my angular application and faced some challenges in integrating it smoothly. The steps I followed were: npm install --save jodit Inserted "node_modules/jodit/build/jodit.min.js" in angular.json's bui ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Tips for maintaining session persistence between requests to an ASP.Net web service when using a Soap client

Here is the setup of my system: A web service implemented using ASP.Net The web service contains a web method with EnableSession set to true A client application references the web service using "Service References" (not "Web References") The app.config ...

"Linking a Next.js application with Azure's Application Insights for advanced insights

Trying to include my Next.js (TypeScript) app logs in Azure Application Insights has been a bit challenging. The documentation provided poor guidance, so I decided to follow this solution: https://medium.com/@nirbhayluthra/integrating-azure-application-ins ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...